Friday, 29 July 2016

Swipe To delete option in UITableView in iOS

Today we will learn how to give swipe to delete option in UITableView in iOS.

1. Create a new Xcode Project (Lets say DefaultDeleteOptionTableView).
2. Now go to Your StoryBoard and take a tableView and a Label.
3. Set the delegate and dataSource for the tableView like this.

4. Your storyboard will look like this

5. Now go to Your ViewController.m and write the following Code.

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@implementation ViewController
    NSMutableArray *tableDataArray;

- (void)viewDidLoad {
    [super viewDidLoad];
    tableDataArray = [[NSMutableArray alloc]initWithObjects:@"Ram",@"Shyam",@"Mohan",@"nilesh", nil];
    // Do any additional setup after loading the view, typically from a nib.

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

#pragma mark - UITableView DataSource Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [tableDataArray count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    cell.textLabel.text = [tableDataArray objectAtIndex:indexPath.row];
    return cell;

#pragma mark - UITableView Delegate Methods

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
         [tableDataArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
       [self.tableView reloadData];

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    // Return NO if you do not want the specified item to be editable.
    return YES;


 Now Run the code and see the desired output.

To download the whole source Code. Please  Click here.
Please have your valuable feedback.
Enjoy Coding :)

No comments:

Post a Comment

Ads Inside Post

Blogger Widget