![](/img/trans.png)
[英]How to get UITableViewCell object from indexPath in Swift?
[英]Get the IndexPath from inside a UITableViewCell subclass in Swift
我有一个自定义的UITableViewCell
子类及其相关的xib。 我在这个单元格中有一个UILabel
和一个UIButton
,我已经将按钮的内部操作连接到子类。
我需要的是点击单元格中的按钮,以获取具有该按钮的单元格的索引路径。 也许可以通过委托或其他东西将其发送回视图控制器。
因为我是里面UITableViewCell
子类,我不能使用的溶液等这个 ,因为我不从小区子类中,必须在tableview中的参考。 经过进一步调查,我找到了另一个解决方案,我在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动态转换失败 。
知道我的代码有什么问题吗?
或者我愿意接受任何其他建议,这些建议可以让我以任何其他方式达到预期的结果。
谢谢。
UIButton.Type确实没有成员superview,但发件人有
var cell: UITableViewCell = sender.superview.superview as UITableViewCell
嘿,你也可以使用按钮的“Tag”。在table委托的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)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.