ios - 在 Swift 中单击表视图单元格时如何显示新的视图控制器
问题描述
单击表格视图单元格时,我试图显示一个新的视图控制器。但我的问题是当我单击表格视图单元格时,新的视图控制器不会出现。我已经看过关于 SO 的解决方案,但没有奏效。
这是故事板的屏幕截图
这是相关的代码:
import UIKit
class RestaurantTableViewController: UITableViewController {
let cellIdentifier: String = "restaurantCell"
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "restaurantSegue" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destination = storyboard.instantiateViewController(withIdentifier: "RestaurantInfoViewController") as! RestaurantInfoViewController
navigationController?.pushViewController(destination, animated: true)
}
}
}
extension RestaurantTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RestaurantTableViewCell
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "restaurantSegue", sender: self)
}
}
注意:我还遵循了Apple's guide链接中的 Apple 文档。但这也不起作用
解决方案
According to the screenshot the segue is connected to the table view cell.
If so delete didSelectRowAt
because the segue is performed directly
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "restaurantSegue", sender: self)
}
The second issue is if you are using a segue you must not call instantiateViewController
.
If you don't have to pass data to the next view controller you can even delete
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "restaurantSegue" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destination = storyboard.instantiateViewController(withIdentifier: "RestaurantInfoViewController") as! RestaurantInfoViewController
navigationController?.pushViewController(destination, animated: true)
}
}
Otherwise get the destination
controller from the segue in prepare(for
and use that.
If the segue is still not performed then there's something wrong with the identifier.
推荐阅读
- python-3.x - 用于图像训练的深度学习
- spring-data-elasticsearch - 使用 ElasticsearchTemplate 索引文档时如何设置路由?
- angular - 删除 Angular 中的动态行
- django - 是否可以访问不同项目中存在的模型/数据库条目?[设置中的数据库名称相同]
- android - 抽屉导航器内的矢量图像不会因不同的屏幕分辨率而改变
- flutter - Dart 多个函数调用/设置变量都在一行上
- .net - PCF 任务调度
- jetty - Jetty:为什么我在网络上只看到 Jetty 计算为 ENABLED 密码的 TLS 密码子集
- jquery - sweetAlert Ajax 删除请求后隐藏元素
- c# - 使用布尔矩阵查找嵌套层次结构