John Smith
John Smith

Reputation: 12807

UITableViewCell with a UIButton

I have UITable which contains some UIButtons. I would like a way to use the label.

The problem I have is that I need two tag labels, one for retrieving the cell in tableviewCellWithReuseIdentifier and configureCell.

Until recently I have been using the UIButton.title to determine which row in the table I selected. The (invisible) text was the row number.

Now I need to use the title for some visible text. How can I still find which row was pressed?

When I press the area outside the button the usual didSelectRowAtIndexPath is called. The hard part is that I want to capture both the UIButton (which calls its own selector) and the row, which I had been finding out from the title. Now I need the title for something else.

Upvotes: 2

Views: 1312

Answers (4)

Matthias Bauch
Matthias Bauch

Reputation: 90127

I use something like this. This will get you the indexpath in the tableview.

- (IBAction)buttonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    CGPoint buttonOriginInTableView = [button convertPoint:CGPointZero toView:tableView];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:buttonOriginInTableView];

    // do something
}

Upvotes: 9

Pavan
Pavan

Reputation: 18548

Implement the UITableViewDelegate protocol. It will help you and do what you need.

didSelectRowAtIndexPath is autmatically called whenever a row is selected in your table.

in your .m file the one with the table view controller if there isn't one there add this method:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   // NSInteger row = [indexPath row];
   // or (indexPath.row)
   // do whatever you like with this value which tells you which row is selected.

}

PK

Upvotes: 0

aegzorz
aegzorz

Reputation: 2219

You should implement the UITableViewDelegate protocol.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Do something based on selected row (indexPath.row)
}

Upvotes: 0

Ben
Ben

Reputation: 2992

You could subclass UITableViewCell or UIButton and add some properties.

Upvotes: 0

Related Questions