Nov 28 2011

Quick iOS tip: invoke UITableView dataSource and delegate methods from a UITableViewCell

Category: Objective-c and CocoaDavide Zanotti @ 6:03 am

I faced a situation in my app where I wanted to access to UITableView datasource from a UITableViewCell. Specifically I implemented the same behavior of left green (+) button in the label contained in the cell, so if you click on it the editing action “UITableViewCellEditingStyleInsert” will be committed.
Since a cell is contained in a table we can easily access to it using self.superview (cast is required because superview returns a basic UIView *), then once we are sure that the table has a valid dataSource, we can manually invoke the selector tableView:commitEditingStyle:forRowAtIndexPath:. In order to pass the proper indexPath dynamically we rely on table method indexPathForCell: (we don’t know in which cell we are but table does!).
The complete code snippet is the following:

1
2
3
4
5
6
7
8
UITableView *table = (UITableView *)self.superview;
SEL sel = @selector(tableView:commitEditingStyle:forRowAtIndexPath:);
   
if ([table isKindOfClass:[UITableView class]] && [table.dataSource respondsToSelector:sel]) {
    [table.dataSource tableView:table
             commitEditingStyle:UITableViewCellEditingStyleInsert
              forRowAtIndexPath:[table indexPathForCell:self]];
}

Tags: , , ,