yosifz8
yosifz8

Reputation: 561

iPhone - Catching an UIButton touch events from a custom cell

i would like to build a custom table view cell and put in him a button and when the user click the button to go to a method-and the method will know which cell the button was pressed.

thx

Upvotes: 0

Views: 1163

Answers (2)

ophychius
ophychius

Reputation: 2653

You can give the button a tag. If you set this tag to be the number of the cells indexPath.row you can always determine from which cell the button was clicked by retrieving the tag Value.

Button tag has to be an integer btw, but sow is indexPath.row.

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    Huis *h = [woningen objectAtIndex:indexPath.row];
    static NSString *identifier = @"Woning";
    WoningTableCell *cell = (WoningTableCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[WoningTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
    }
    [cell setNewWoning:h withIndex:indexPath.row];
    return cell;
}

Here I create a custom cell displaying details of a 'Huis'. When setting the object for the cell I also pass the indexPath.row of the cell that I am filling.

Then in the custom cell, upon setting the object, I also set the tag value for my button like this:

UIButton *indexBtn = [UIButton .... ];
indexBtn.tag = indexRowInteger;

The button might have already been created / initialized, in that case you only set the tag. Now in the function handling your ControlEvent you can access this tag like so:

- (void) CellButtonPressed: (id) sender{

UIButton *b = ((UIButton *)sender);
NSInteger tagValue = btn.tag;

}

Upvotes: 0

nambi
nambi

Reputation: 547

- (void) cellButtonClicked: (id) sender 
{
  UIButton *btn = (UIButton *) sender;
  UITableViewCell *cell = (UITableViewCell *) [[btn superview] superview];
  NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  //do something with indexPath...
}

Hope this work

Upvotes: 4

Related Questions