0

I subclassed UITableViewCell and added a button to it. How do I response to the event when the button is touched? I also need to know which index path was the button pressed on.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomTableCell";

    CustomTableCell *cell = (CustomTableCell *)
    [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle]
                                    loadNibNamed:@"CustomTableCell"
                                    owner:nil options:nil];
        for (id currentObjects in topLevelObjects){
            if ([currentObjects isKindOfClass:[StatusTableCell class]]){
                cell = (StatusTableCell *) currentObjects;
                break;
            }
        }                           
    }
    cell.customButton.tag = indexPath.row;
    return cell;
}
John2
  • 15
  • 1
  • 4
  • [refer to this link][1] [1]: http://stackoverflow.com/questions/869421/using-a-custom-image-for-a-uitableviewcells-accessoryview-and-having-it-respond – HelmiB Sep 19 '11 at 04:43

2 Answers2

4

If you have added the UIButton by code in your UITableViewCell Subclass you can use the following code to add an action for it.

//In UITableViewCell subclass
    [customButton addTarget:self 
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchDown];

And then you have already written the code for accessing the row number by setting,

 cell.customButton.tag = indexPath.row;

You can get the tag value in the aMethod and access the indexPath.row value like below,

//In UITableViewCell subclass
    -(IBAction)aMethod:(UIButton*)button
    {
        NSLog(@"indexPath.row value : %d", button.tag);
    }
sElanthiraiyan
  • 6,000
  • 1
  • 31
  • 38
2

You can assign the IBAction in the CustomTableCell Nib and in the function do something like this:

- (IBAction) btnDoSomethingPressed:(id)sender {
    NSIndexPath *indexPath = [yourTableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
     //Use indexPath (or indexPath.row) like you would in a UITableViewDelegate method 
}

This assumes that yourTableView is an instance variable assigned to your table.

Mark Armstrong
  • 819
  • 6
  • 9