Vincent Vincent - 4 years ago 284
Swift Question

swift: how to get the indexpath.row when a button in a cell is tapped?

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 = Int()
func buttonPressed(sender: AnyObject) {
let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
println(cellIndexPath)
point = cellIndexPath!.row
println(point)
}

Answer Source

giorashc almost had it with his answer, but there was one more line of code that was required. The correct answer would be:

    let button = sender as! UIButton
    let view = button.superview!
    let cell = view.superview as! <Your custom cell name here>

    let indexPath = itemTable.indexPathForCell(cell)

This is because within the view heirarchy a tableView has cells as subviews which susequently have their own 'content views' this is why you must get the superview of this content view to get the cell itself.

Hope this helps,

Jacob

EDIT:

As per the comment I received with regard to force unwrapping in swift, should you not want to force unwrap, you can unwrap safely using an if let clause as follows:

var indexPath: Int!

if let button = sender as? UIButton {
    if let superview = button.superview {
        if let cell = superview.superview as? MyCellClassHere {
            indexPath = itemTable.indexPathForCell(cell)
        }
    }
}

// Check for indexPath value, if any, here.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download