iPhone Development 101

iPhone 101

Code Tips

Resources

Links

Follow

Mailing ListTwitter

More

iPhone Development 101: User Interface: UITableView:
UITableView: Buttons Inside Cells

Sometimes it's handy to use your own buttons inside a table view cell, and have a separate IBAction method to handle button presses (instead of the table's didSelectRowAtIndexPath method, which handles row presses). In order to figure out which row contains the button pressed, you can use the following code to find the parent cell:

-(UITableViewCell *)parentCellForView:(id)theView 
{
    id viewSuperView = [theView superview];
    while (viewSuperView != nil) {
        if ([viewSuperView isKindOfClass:[UITableViewCell class]]) {
            return (UITableViewCell *)viewSuperView;
        }
        else {
            viewSuperView = [viewSuperView superview];
        }
    }
    return nil;
}

Then in your button handler method, call the above method to get the parent cell, and then the table view's indexPathForCell: to get the indexPath. (This assumes you have a @property defined for the table view; in this case the property name is theTableView. For simple tables you can also use cell.superview to get the table view object.)

-(IBAction)showDetail:(id)sender 
{
    UIButton *butn = (UIButton *)sender;
    UITableViewCell *cell = [self parentCellForView:butn];
    if (cell != nil) {
        NSIndexPath *indexPath = [theTableView indexPathForCell:cell];
        NSLog(@"show detail for item at row %d", indexPath.row);
    }
}

TopHome