swift - 按下按钮时,如何将表格视图中单元格的索引从一个视图控制器传递到下一个视图控制器?
问题描述
每次我尝试执行以下操作时,它将索引传递给下一个视图控制器为 0。我不确定我做错了什么,有人可以帮忙吗?非常感谢!以下是相关代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "a", for: indexPath) as! TableViewCell
cell.useButton.tag = tagBaseValue + indexPath.row
cell.useButton.addTarget(self, action: #selector(ListViewController.useButtonPressed(_:)), for: UIControlEvents.touchUpInside)
return cell
}
@IBAction func useButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "toDisplay", sender: self)
}
func prepare(for segue: UIStoryboardSegue, sender: UIButton) {
if segue.identifier == "toDisplay" {
let nextVC = segue.destination as! NextVC
nextVC.index = sender.tag
}
}
解决方案
prepare(for
永远不会因为签名错误而被调用(类型sender
is Any?
)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDisplay" {
let nextVC = segue.destination as! NextVC
nextVC.index = (sender as! UIButton).tag
}
}
并且IBAction
必须是
@IBAction func useButtonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "toDisplay", sender: sender)
}
推荐阅读
- android - 如何在 AOSP 源代码中添加预构建的应用程序(系统应用程序)
- php - 跨所有相关数组键同步数组值
- docker - kind cluster - 如何查看已加载的 docker-images?
- python - 在什么情况下看起来像 python 内存泄漏的问题不是泄漏?
- python - SqlAlchemy 为 ColumnClause 分配不同的列名
- perl - 使用承认/呱呱/咯咯省略错误处理程序的最顶层调用者?
- postgresql - 在 psql 客户端中使用 LISTEN / NOTIFY
- windows - 批处理文件找不到脚本中指定的扩展文件
- validation - 验证实体的属性值,没有不需要的依赖项
- math - 为什么相关在信号匹配中使用乘法而不是减法?