Get the IndexPath from inside a UITableViewCell su

2019-06-14 22:43发布

问题:

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.

回答1:

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)



回答2:

UIButton.Type really does not have member superview, but sender have

var cell: UITableViewCell = sender.superview.superview as UITableViewCell



回答3:

Hey you can use "Tag" of the button also.Inside the cellForRowAt method of table delegate u can tag the button with Indexpath.row . here is the example what i m tried to say.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// get ur cell nib .As it has a button
cell.startOrConntinuBtn.addTarget(self, action: #selector(sumbitOrContinue), for: .touchUpInside) 

cell.startOrConntinuBtn.tag = indexPath.row }

and in the touch method "sumbitOrContinue" -

 func sumbitOrContinue(sender: UIButton!) { 
let tag = sender.tag
// do what you want to do like this example

let detail = self.detailList[tag]
let vc  = self.storyboard?.instantiateViewController(withIdentifier: "mockExamInt") as! MockWindowVc
vc.detailId = detail.id
self.navigationController?.pushViewController(vc, animated: true)}