问题描述
我正在尝试执行 segue 并希望使用所选单元格的文本来控制在新屏幕上显示的信息。我可以使用 IBaction 来执行转场,但目前还无法弄清楚如何获取单元格信息。所以我然后尝试使用 func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) 和 didselectrowat 但都没有工作。我已经尝试删除 IBaction 并删除按钮来消除无效参数 NSexception 错误,但是当我点击单元格时绝对没有。 我已经包含了我的代码,并且在当前形式下,虽然没有显示任何信息,但确实发生了 segue。如果我删除 IBaction 行并从故事板中删除按钮,则什么都没有。请为我指明正确的方向。
// func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
@IBAction func segueToDriverRDWList(_ sender: UIButton) {
print("SEGUE")
performSegue(withIdentifier: "gotodriverRDWlist",sender: self)
}
override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
let destinationVC = segue.destination as! DriverRDWViewController
// destinationVC.selectedDriver = driverNameArray[indexPath.row]
// print(driverNameArray[indexPath.row])
}
解决方法
据我所知,您还没有确认 UItableview 的数据源和委托方法,这就是 didselect 方法不起作用的原因。请参阅此了解更多详情 https://shrikar.com/uitableview-delegate-and-datasource-in-swift/#:~:text=Create%20a%20new%20file%20called%20MainViewController.,tableview%20for%20that%20particular%20section。
,您不需要@IBAction,只需使用didSelectRowAt,并且您的类必须符合UITableViewDelegate 和UITableViewDataSource 协议(dataSource 和delegate 也必须设置为self):
override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
if segue.identifier == "gotodriverRDWlist" {
let destinationVC = segue.destination as! DriverRDWViewController
//Pass your data here
}
}
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "gotodriverRDWlist",sender: nil)
}