Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the IndexPath from inside a UITableViewCell subclass in Swift

Tags:

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.

like image 521
Isuru Avatar asked Sep 16 '14 11:09

Isuru


People also ask

How do I get IndexPath in Swift?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

What does IndexPath row return?

row will be 0. Then it will be 1, then 2, then 3 and so on. You do this so that you can get the correct string from the array each time.

What is IndexPath section Swift?

In Swift, an indexPath is a list of indexes that, together, represent the path to a specific location in a tree of nested arrays. It describes an item's position inside a table view or collection view, storing both its section and its position inside that section.


1 Answers

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)

like image 130
ullstrm Avatar answered Sep 30 '22 12:09

ullstrm