Saturday 16 April 2016

Add multiple buttons to a UITableView cell on swipe

When we want to add some action to a table view cell when swipe , Apple provides the methods to deal with it. But by default Apple gives only one button when we swipe to left, a delete button . But what if we want more buttons like a mail app in iOS 8.

In iOS8 Apple provides this functionality in form of edit actions and UITableViewRowAction.

To use UITableViewRowAction we have to implement a delegate method of UITableView:

-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    //return an array of UITableViewRowAction instances
}
In this method we create the UITableViewRowAction instance like this:

UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
       
        //call method to perform action when user tap on delete button   
    }];

The above code will create a delete instance and provide handler block which will be executed when user tap on the targeted  UITableViewRowAction instance.

Like this we can create multiple instances of the UITableViewRowAction  and finally return an array of UITableViewRowAction instances.

How that's simple it is to add multiple button to a table view cell on swipe.But to enable user to perform action on these multiple buttons we have to enable users to allow editing on the table view cell. To do this, implement these two table view delegate methods:

To allow editing on cell, implement:

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

It is necessary to override this second method, even though we can leave it blank. If method is not present the action won't show up on swipe.

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //to do when commiting editing
}