ios - 如何从 didSelectRowAt 执行 segue
问题描述
我坚持这个简单的任务来从选定的单元格执行 segue。
我已经创建了一个从一个 ViewController 到另一个具有标识符“showDetails”的 segue。比我尝试这段代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetails",
let destination = segue.destination as? DetailsViewController {
let indexPath = tableView.indexPathForSelectedRow!
destination.rideIndex = indexPath.row
}
}
显然它不起作用。我究竟做错了什么?
解决方案
检查 UITableView 委托,并确保您将 segue 设置为“Present Modally or show”,并且:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetails" {
let destination = segue.destination as! DetailsViewController
let indexPath = tableView.indexPathForSelectedRow!
destination.rideIndex = indexPath.row
}
}
但我个人更喜欢下面的代码来打开 UIViewController:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let destination = mainStoryboard.instantiateViewController(withIdentifier: "DetailsViewController") as! DetailsViewController
let indexPath = tableView.indexPathForSelectedRow!
destination.rideIndex = indexPath.row
self.present(destination, animated: true, completion: nil)
}
并确保您的 DetailsViewController 具有标识符“DetailsViewController”