从Swift中的UITableViewCell子类中获取IndexPath

时间:2014-09-16 11:21:45

标签: ios uitableview swift uibutton nsindexpath

我有一个自定义UITableViewCell子类及其关联的xib。我在这个单元格中有一个UILabel和一个UIButton,我已经将按钮的内部操作连接到子类。

我需要的是点击单元格中的按钮,以获取具有该按钮的单元格的索引路径。也许可以通过委托或其他方式将其发送回视图控制器。

由于我在UITableViewCell子类中,我不能使用像this这样的解决方案,因为我没有从单元子类内部引用tableview。经过进一步调查,我找到了another解决方案,我在Swift中实现了这个。

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")
    }

}

但是当我点击按钮时,它会崩溃并显示一条错误消息,指出 Swift动态广告失败

知道我的代码有什么问题吗?

或者我对其他任何可以让我以任何其他方式达到预期结果的建议持开放态度。

谢谢。

3 个答案:

答案 0 :(得分:22)

听起来你需要一个代表:

Delegates in swift?

然后将单元格本身作为参数传递给委托,然后您可以轻松地执行tableView.indexPathForCell(cellFromDelegateMethod)

答案 1 :(得分:2)

UIButton.Type确实没有成员超级视图,但发件人有

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

答案 2 :(得分:2)

嘿,你可以使用" Tag"也就是按钮的内部。在表委托的cellForRowAt方法中,你可以用Indexpath.row标记按钮。这是我试图说的例子。

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 }

和触摸方法" 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)}
相关问题