initlaunch
initlaunch

Reputation: 467

UITableView cells with buttons

I want to have a UIButton in each UITableViewCell that will allow me to perform selector on the object corresponding to that row. They way I got it working was to create a separate UITableViewCell for each row (no reuse), add a new UIButton that is tagged with the row. When the button gets tapped, the resulting selector checks the tag of the sender to determine which object to change.

Is there a better way of doing this? For one, I am not reusing cells which is unfortunate, and using UIView.tag seems very hacky.

Upvotes: 0

Views: 596

Answers (2)

Elias
Elias

Reputation: 519

You can use the same tag number on all of the UIButtons.

To extract the row number which has been clicked, implement this code in the selector:

- (void)buttonClicked:(id)sender

{

    UITableViewCell * clickedCell = (UITableViewCell *)[[sender superview] superview];

    NSIndexPath * clickedButtonPath = [self.tableView indexPathForCell:clickedCell];

    int rownumber = clickedButtonPath.row;
}

Upvotes: 6

fearmint
fearmint

Reputation: 5334

I would make a subclass of UITableViewCell so that it stores a reference to a button. Then set that button when you dequeue a cell. In the method that is called, sender will be the button and you can ask for it's superview and then ask that (which is the cell) for it's index.

Upvotes: 0

Related Questions