从 Swift 中的 UITableViewCell 子类中获取 IndexPath [英] Get the IndexPath from inside a UITableViewCell subclass in Swift

查看:100
本文介绍了从 Swift 中的 UITableViewCell 子类中获取 IndexPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

由于我在 UITableViewCell 子类中,所以我不能使用像 this 因为我没有从单元格子类内部对 tableview 的引用.经过进一步调查,我发现了另一个解决方案,我在 Swift 中像这样实现了它.

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

}

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

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.

谢谢.

推荐答案

听起来你需要一个委托:

Sounds like you need a delegate:

快速的代表?

然后只需将单元格本身作为参数传递给委托,然后就可以轻松做到tableView.indexPathForCell(cellFromDelegateMethod)

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

这篇关于从 Swift 中的 UITableViewCell 子类中获取 IndexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆