How to get the indexpath.row when an element is activated?

前端 未结 19 2600
梦如初夏
梦如初夏 2020-11-21 23:30

I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped. This is what I currently have, but it always is 0

var point =         


        
19条回答
  •  半阙折子戏
    2020-11-21 23:58

    UPDATE: Getting the indexPath of the cell containing the button (both section and row):

    Using Button Position

    Inside of your buttonTapped method, you can grab the button's position, convert it to a coordinate in the tableView, then get the indexPath of the row at that coordinate.

    func buttonTapped(_ sender:AnyObject) {
        let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView)
        let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
    }
    

    NOTE: Sometimes you can run into an edge case when using the function view.convert(CGPointZero, to:self.tableView) results in finding nil for a row at a point, even though there is a tableView cell there. To fix this, try passing a real coordinate that is slightly offset from the origin, such as:

    let buttonPosition:CGPoint = sender.convert(CGPoint.init(x: 5.0, y: 5.0), to:self.tableView)
    

    Previous Answer: Using Tag Property (only returns row)

    Rather than climbing into the superview trees to grab a pointer to the cell that holds the UIButton, there is a safer, more repeatable technique utilizing the button.tag property mentioned by Antonio above, described in this answer, and shown below:

    In cellForRowAtIndexPath: you set the tag property:

    button.tag = indexPath.row
    button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    

    Then, in the buttonClicked: function, you reference that tag to grab the row of the indexPath where the button is located:

    func buttonClicked(sender:UIButton) {
        let buttonRow = sender.tag
    }
    

    I prefer this method since I've found that swinging in the superview trees can be a risky way to design an app. Also, for objective-C I've used this technique in the past and have been happy with the result.

提交回复
热议问题