我有一个自定义的UITableViewCell
子类及其关联的xib。我在这个单元格中有一个UILabel
和UIButton
,我已经将按钮的内部触摸操作连接到子类。
我需要的是当点击单元格中的按钮时,获得具有该按钮的单元格的索引路径。也许可以通过委托或其他方式将其发送回视图控制器。
由于我在UITableViewCell
子类中,所以我不能使用这样的解决方案,因为我没有从单元格子类中引用表视图。经过进一步的调查,我找到了另一个解决方案,并在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动态转换失败。
知道我的代码出了什么问题吗?
或者,我愿意接受任何其他建议,这些建议可以让我以任何其他方式达到预期的结果。
谢谢。
听起来你需要一个代理人:
代表在swift?
然后只需将单元格本身作为参数传递给委托,就可以轻松地执行tableView.indexPathForCell(cellFromDelegateMethod)
嘿,你也可以使用按钮的"Tag"。在表delegate的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)}
UIButton.Type确实没有成员超视图,但发送方有
var cell: UITableViewCell = sender.superview.superview as UITableViewCell