iPhone - How to determine in which cell a button was pressed in a custom UITableViewCell

后端 未结 10 1912
遥遥无期
遥遥无期 2021-01-01 15:45

I currently have a UITableView that is populated with a custom UITableViewCell that is in a separate nib. In the cell, there are two buttons that are wired to actions in th

相关标签:
10条回答
  • 2021-01-01 16:19

    this solution also works in IBAction connected using storyboard cell prototype

    - (IBAction)viewMapPostsMarker:(UIButton*)sender{
        // button > cellContentView > cellScrollView > cell
        UITableViewCell *cell = (UITableViewCell *) sender.superview.superview.superview; 
        NSIndexPath *index = [self.mapPostsView indexPathForCell:cell];
        NSLog(@" cell at index %d",index.row);
    }
    
    0 讨论(0)
  • 2021-01-01 16:22

    You can access the buttons superview to get the UITableViewCell that contains your button, but if you just need the row number, you can use the tag property like the previous post deacribes.

    0 讨论(0)
  • 2021-01-01 16:28

    Here's a Swift example...

    The UIControl class is the superclass of various iOS widgets, including UIButton, because UIControl provides the target/action mechanism that sends out the event notifications. Therefore a generic way to handle this is as follows:

    func actionHandler(control: UIControl)
       var indexPath = tableView.indexPathForCell(control.superview!.superview! as UITableViewCell)!
       var row = indexPath.row
    }
    

    Here's an example of setting up a button control to deliver the action. Alternatively, create an @IBAction and create the action visually with Interface Builder.

    button.addTarget(self, action: "actionHandler:", forControlEvents: .TouchUpInside)
    

    You can downcast UIControl parameter to UIButton, UIStepper, etc... as necessary. For example:

    var button = control as UIButton
    

    The superview of control is the UITableViewCell's contentView, whose subviews are the UIViews displayed in the cell (UIControl is a subclass of UIView). The superview of the content cell is the UITableViewCell itself. That's why this is a reliable mechanism and the superviews can be traversed with impunity.

    0 讨论(0)
  • For a implementation that is not dependent on tags or the view hierarchy do the following

    - (void)btnPressed:(id)sender event:(id)event
    {
      UITouch *touch = [[event allTouches] anyObject];
      CGPoint touchPoint = [touch locationInView:self.tableView];
      NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
    }
    
    0 讨论(0)
提交回复
热议问题