首页 > 解决方案 > 在 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 文档。但这也不起作用

标签: iosswiftuitableview

解决方案


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.


推荐阅读