John2
John2

Reputation: 15

Custom UITableViewCell with button

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;
}

Upvotes: 0

Views: 3810

Answers (2)

Mark Armstrong
Mark Armstrong

Reputation: 839

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.

Upvotes: 2

sElanthiraiyan
sElanthiraiyan

Reputation: 6268

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);
    }

Upvotes: 4

Related Questions