Get the IndexPath from inside a UITableViewCell subclass in Swift

Isuru picture Isuru · Sep 16, 2014 · Viewed 25.3k times · Source

I have a custom UITableViewCell subclass and its associated xib. I have a UILabel and a UIButton in this cell and I have wired the touch up inside action of the button to the subclass.

What I need is when that button in the cell is tapped, to get the indexpath of the cell which has that button. And maybe send it back to the view controller via a delegate or something.

Since I'm inside a UITableViewCell subclass, I can't use a solution like this because I don't have a reference to the tableview from inside the cell subclass. Upon further investigation I found another solution and I implemented it in Swift like this.

import UIKit

class ContactCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        selectionStyle = .None
    }

    @IBAction func callButtonPressed(sender: UIButton) {
        let indexPath = (self.superview as UITableView).indexPathForCell(self)
        println("indexPath?.row")
    }

}

But when I tap on the button, it crashes with an error message saying Swift dynamic cast failed.

Any idea what's wrong with my code?

Or I'm open to any other suggestions which would allow me to achieve the desired result in any other way.

Thank you.

Answer

ullstrm picture ullstrm · Sep 16, 2014

Sounds like you need a delegate:

Delegates in swift?

Then just pass the cell itself as a parameter to the delegate, and then you can easily do tableView.indexPathForCell(cellFromDelegateMethod)