【发布时间】:2021-02-24 11:54:14
【问题描述】:
在 FirstVC 上我有一个变量索引:
var index = -1
,它保存了单元格 indexPath.row 的信息,这样我就可以知道在哪个单元格中点击了按钮。 (每个单元格都有自己的按钮)
我试过这样:CellForRow:
cell.Btn.tag = indexPath.row
cell.Btn.addTarget(self, action: #selector(detectButton), for: .touchUpInside)
然后:
@objc func detectButton(sender: UIButton) {
self.index = sender.tag
}
第二个VC是通过segue连接的,所以我尝试像这样发送索引:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MySegue" {
let vc = segue.destination as! SecondVC
vc.element = self.elements[index]
}
}
它在那里崩溃,因为索引仍然是-1。我以为@objc func detectButton
将在prepareForSegue 之前调用,但不是。
为什么?还有其他解决方案可以将索引发送到 secondVC 吗?
【问题讨论】:
-
是什么导致
prepareForSegue被调用? -
第一次使用 segues,因为我不得不这样做。 Segue 是通过单元格中的按钮在情节提要中定义的。
标签: ios swift uitableview uibutton segue