Warm tip: This article is reproduced from serverfault.com, please click

Find the indexPath of a button inside UITableViewCell when button pressed?

发布于 2014-11-24 13:25:49

The code below correctly returns the cell:

func findSuperView(sender:UIButton!) -> UITableViewCell { 
    var superView : UIView? = sender.superview 
    var foundSuperView : UITableViewCell! 

    while superView != nil && foundSuperView == nil { 
        if let cell = superView as? UITableViewCell { 
            foundSuperView = cell 
            break 
        } 
        else { 
            superView = superView?.superview 
        } 
    } 
    return foundSuperView 
}

But for finding indexpath in tableview it crashes:

var indexPath : NSIndexPath = self.table .indexPathForCell(findSuperView(sender))!
println("Section (indexPath)")

And I tried another way, but it was not successful:

var button : UIButton = sender as UIButton; 
var touch: UITouch = events .allTouches()?.anyObject() as UITouch 
var location : CGPoint = touch.locationInView(self.table) 
var indexPath : NSIndexPath = self.table.indexPathForRowAtPoint(location)!
Questioner
Arsalan Ansari
Viewed
0
vacawama 2015-12-11 19:26:26

I don't know if there is an easy a way to do this. (Edit: Actually there is. Look at @mustafa's second solution.) A workaround is to set the button's tag to indexPath.row in cellForRowAtIndexPath, then you can just access the button's tag to find out which row it belongs to.

Warning: This workaround is fragile. It won't work correctly if you allow rows to be added or deleted from your table without then calling tableView.reloadData(). Look at @mustafa's solution which is much more robust.