[英]Detecting cell whose button was tapped
On the FirstVC I have a variable index:在 FirstVC 上我有一个变量索引:
var index = -1
, which keeps the information of cell's indexPath.row so I can know in which cell the button was tapped. ,它保留了单元格的 indexPath.row 信息,因此我可以知道在哪个单元格中点击了按钮。 (Each cell has its own button) (每个单元格都有自己的按钮)
I tried like this:我试过这样的:
CellForRow
: CellForRow
:
cell.Btn.tag = indexPath.row
cell.Btn.addTarget(self, action: #selector(detectButton), for: .touchUpInside)
and then:接着:
@objc func detectButton(sender: UIButton) {
self.index = sender.tag
}
The secondVC is connected by the segue so I tried to send the index like this: secondVC 由 segue 连接,所以我尝试像这样发送索引:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MySegue" {
let vc = segue.destination as! SecondVC
vc.element = self.elements[index]
}
}
It crashes there because the index was still -1
.它在那里崩溃是因为索引仍然是-1
。 I thought that @objc func detectButton
will be called before prepareForSegue
but it is not.我认为@objc func detectButton
将在prepareForSegue
之前被调用,但事实并非如此。
Why?为什么? And is there any other solution to send the index to the secondVC?还有其他解决方案可以将索引发送到 secondVC 吗?
Reconnect the segue from the view controller (rather than from the table view cell) to the destination controller将 segue 从视图 controller (而不是从表视图单元格)重新连接到目标 controller
Delete var index = -1
删除var index = -1
Replace代替
@objc func detectButton(sender: UIButton) { self.index = sender.tag }
with (note the underscore after the open parentheses) with(注意左括号后的下划线)
@objc func detectButton(_ sender: UIButton) { performSegue(withIdentifier: "MySegue", sender: sender.tag) }
Replace代替
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MySegue" { let vc = segue.destination as. SecondVC vc.element = self.elements[index] } }
with和
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MySegue" { let vc = segue.destination as. SecondVC let index = sender as. Int vc.element = self.elements[index] } }
Edit:编辑:
Apparently in the current segue setup the button triggers the segue.显然在当前的 segue 设置中,按钮触发了 segue。 If so delete var index = -1
and also the line cell.Btn.addTarget...
(but not the line to assign the tag) and the entire method @objc func detectButton(_ sender: UIButton) {... }
.如果是这样,请删除var index = -1
以及行cell.Btn.addTarget...
(但不是分配标签的行)和整个方法@objc func detectButton(_ sender: UIButton) {... }
。
In prepare(for segue
get the tag from the sender
parameter在prepare(for segue
从sender
参数中获取标签
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MySegue" { let vc = segue.destination as. SecondVC let index = (sender as. UIButton).tag vc.element = self.elements[index] } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.