我有一个自定义的UITableViewCell
子类及其关联的xib。我在这个单元格中有一个UILabel
和一个UIButton
,并且我已经将按钮的touch up内部动作连接到了子类。
我需要的是当单元格中的按钮被点击时,以获得具有该按钮的单元格的索引路径。并可能通过委托或其他方式将其发送回视图控制器。
因为我在UITableViewCell
子类中,所以不能使用像this这样的解决方案,因为我没有从cell子类中引用表视图。经过进一步的研究,我找到了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 dynamic cast failed。
你知道我的代码出了什么问题吗?
或者,我对任何其他的建议持开放态度,这些建议可以让我以任何其他方式达到预期的结果。
谢谢。
发布于 2014-09-16 19:29:54
听起来你需要一个代理:
然后,只需将单元格本身作为参数传递给委托,然后就可以轻松地执行tableView.indexPathForCell(cellFromDelegateMethod)
发布于 2017-01-24 13:27:19
嘿,你可以使用按钮的“also.Inside”,表代理的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)}
发布于 2015-01-20 21:00:30
UIButton.Type确实没有成员superview,但发件人有
var cell: UITableViewCell = sender.superview.superview as UITableViewCell
https://stackoverflow.com/questions/25867439
复制相似问题