Table view with insert and delete rows in iPhone

A very common feature for almost all iOS applications is UITableView and its data source and delegate protocol. In this tutorial I will explain how to edit table view rows with little animations. i.e I will discuss how to delete and insert a row within the table view.
Open Xcode and proceed with the single view application template. In AppDelegate.m file modify the code such that ViewController becomes the root view of the navigation controller by adding the following code.

UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController: self.viewController];
self.window.rootViewController = navController;

In ViewController.xib file drag UITableView object and connect it with the associated outlet in .h file. Also register with UITableView data source and delegate protocols. Now open ViewController.h file and modify as follows.

@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) IBOutlet UITableView *aTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

(void)addORDeleteRows;

@end

Open viewDidLoad method of ViewController.m file and add the below code.

self.dataArray = [[NSMutableArray alloc] initWithObjects:@"Tiger",@"Leopard",@"Snow Leopard",@"Lion",nil];
self.title = @"Data Table";
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style: UIBarButtonItemStyleBordered target:self action:@selector(addORDeleteRows)];[self.navigationItem setLeftBarButtonItem:addButton];

Here dataArray contains string objects which we display in table view. Our purpose of this tutorial is editing table view in such a way to delete or insert rows. For that we need a bar button on top of navigation bar. Hence I added UIBarButtonItem named Edit and registered its action with addORDeleteRows method. Now we need to implement this method by adding the following lines of code.

(void)addORDeleteRows
{
    if(self.editing)
        {
                [super setEditing:NO animated:NO];
                [aTableView setEditing:NO animated:NO];
                [aTableView reloadData];
                [self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
                [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
        }
        else
        {
                [super setEditing:YES animated:YES];
                [aTableView setEditing:YES animated:YES];
                [aTableView reloadData];
                [self.navigationItem.leftBarButtonItem setTitle:@"Done"];
                [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];
        }
}

From the above code, the property “editing” is a boolean type variable which indicates whether table view is in edit mode or not. Else part of if statement contains other variation of Edit button. i.e. after tapping edit button, table view becomes editable and our button text changed to Done. Now we need to implement the table view data source methods for number of rows and its content. Add the following code into your project.

(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        int count = [self.dataArray count];
        if(self.editing) count++;
        return count;
}

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.editingAccessoryType = YES;
    }
    int count = 0;
        if(self.editing && indexPath.row != 0)
                count = 1;
       
        if(indexPath.row == ([self.dataArray count]) && self.editing){
                cell.textLabel.text = @"Append a new row";
                return cell;
        }
        cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

The numberOfRowsInSection method returns one extra row if the table view is in edit mode otherwise it returns the dataArray count. In edit mode cellForRowAtIndexPath method returns an extra cell with content “Append a new row” at the end of table view. Now compile and run the code you will see the following screens in normal and edit modes.



In edit mode all the rows are preceded with “-” icon including last row. The purpose of last row is to add the new row at the end of table view. So we need to change the icon of last row. This is possible by adding editingStyleForRowAtIndexPath delegate method.

(UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editing == NO || !indexPath)
        return UITableViewCellEditingStyleNone;
   
    if (self.editing && indexPath.row == ([self.dataArray count]))
                return UITableViewCellEditingStyleInsert;
        else
                return UITableViewCellEditingStyleDelete;
   
    return UITableViewCellEditingStyleNone;
}

Now compile and run the code you will see the following screen.

No action will be performed if you tap either on “-” icon’s Delete button or “+” icon. To delete a row or insert a row at the end of table view we need to over write the UITableViewDataSource method commitEditingStyle as follows.

(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{      
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [self.dataArray removeObjectAtIndex:indexPath.row];
                [aTableView reloadData];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        [self.dataArray insertObject:@"New version" atIndex:[self.dataArray count]];
                [aTableView reloadData];
    }
}

Build and run the code, now you will able to insert and delete the rows.

Leave a Reply

Your email address will not be published. Required fields are marked *