开发者

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

开发者 https://www.devze.com 2023-02-01 16:49 出处:网络
I have created but开发者_如何学Pythontons on the cell content view. I want to detect for which row the button is clicked on.You\'ll need to have your UIViewController receive the event by creating a t

I have created but开发者_如何学Pythontons on the cell content view. I want to detect for which row the button is clicked on.


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消