Warrior
Warrior

Reputation: 39374

Detect the cell row value on tap of a button in that cell in iPhone?

I have created buttons on the cell content view. I want to detect for which row the button is clicked on.

Upvotes: 3

Views: 1607

Answers (4)

OhadM
OhadM

Reputation: 4803

You can achieve that with a simpler solution.

Since in most of the cases each cell represent an object inside an array, you need to define a property in the custom cell class that represent a cell id (in your array) or the cell id that is defined in the server DB and when the button was tapped you can easily get it via self.id - id represent the cell id property.

Upvotes: 0

Edward Huynh
Edward Huynh

Reputation: 2917

This is an alternative that doesn't fall over when apple changes the view hierarchy. Basically find the origin of the button in the coordinate system of the table view. Once you know that you can find the NSIndexPath of the row that the point is in.

- (void)buttonTapped:(UIButton *)button
{
    CGPoint buttonOrigin = [button convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonOrigin];
}

Upvotes: 2

djdance
djdance

Reputation: 3209

agree to Will, you have to iterate in iOs7

for (UIView *parent = [btn superview]; parent != nil; parent = [parent superview]) {
    if ([parent isKindOfClass: [UITableViewCell class]]) {
        UITableViewCell *cell = (UITableViewCell *) parent;
        NSIndexPath *indexPath = [self.tableView indexPathForCell: cell];
        break;
    }
}

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163228

You'll need to have your UIViewController receive the event by creating a target-action from the UIButton to the UIViewController, like this:

[button addTarget:self action:@selector(cellButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

Then in your UIViewController's action method, you can utilize the UITableViews indexPathForCell: method to obtain the correct NSIndexPath:

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

Upvotes: 5

Related Questions