iPhone custom button within a UITableViewCell

Hello everyone,

This is a simple tutorial to demonstrate a common task involved with a custom tableview in iOS development. This situation is where you would want to add a button to each cell for another option of user interaction rather than just the cell selection. The common problem is to determine which cell the button belongs to on the event that its pressed.

I have created a simple project to demonstrate this which can be downloaded here: Example Project

Before you begin you should be comfortable with the work with basic tableviews

First the set up of our cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
         .......
	cell.textLabel.text = [NSString stringWithFormat:@"Cell #%i", indexPath.row + 1];

	//Create the button and add it to the cell
	UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[button addTarget:self
			   action:@selector(customActionPressed:)
	 forControlEvents:UIControlEventTouchDown];
	[button setTitle:@"Custom Action" forState:UIControlStateNormal];
	button.frame = CGRectMake(150.0f, 5.0f, 150.0f, 30.0f);
	[cell addSubview:button];

    return cell;
}

Pretty simply we are creating a UIButton and pointing it to our button pressed function and adding it to the cell.

Handle the button press:

	//Get the superview from this button which will be our cell
	UITableViewCell *owningCell = (UITableViewCell*)[sender superview];

	//From the cell get its index path.
	NSIndexPath *pathToCell = [myTableView indexPathForCell:owningCell];

        //Do something with our path

In this case our sender is the UIButton which fires the call so its superview is the cell that we originally added it to. From the cell we can retrieve its indexPath from the tableview its in.

Once we have the indexPath we would most likely use it to do some work from that index in our array that might be the data source for the table.

Thats basically it. In my example I have alert views which are used to give some feed back when you press a button or a cell but this is a good start to creating a more customized tableview.

I hope this tutorial helps and if you have any comments or questions please email me or leave a comment.

-Ryan