无法推送到导航控制器

Unable to push to navigation controller

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 1: try loading the "Detail" view controller and typecasting it to be DetailViewController
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        // 2: success! Set its selectedImage property
        vc.selectedImage = pictures[indexPath.row]

        // 3: now push it onto the navigation controller
        navigationController?.pushViewController(vc, animated: true)
    }
}

我面临问题 - 1.Cast 从 'UIViewController?' 到无关类型 'DetailViewController' 总是失败 2.Cannot 将类型 'DetailViewController' 的值转换为预期的参数类型 'UIViewController'

DetailViewController 似乎不是 UIViewController 的子类。您可以通过如下修改 DetailViewController 定义来简单地解决此问题:

class DetailViewController: UIViewController {
...
}

Cast from 'UIViewController?' to unrelated type 'DetailViewController' always fails

确保您的 DetailViewControllerUIViewController

的子类
class DetailViewController: UIVieController {

您也可以使用另一种方法来避免 storyboard?.instantiateViewController(withIdentifier:) method(并避免故事板 ID 可能出现的错误):从原型 tableView 单元格添加一个 segue 到故事板上的视图控制器

然后在拥有 tableView:

的 viewController 的 prepare(for segue) 方法中配置 detailViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? DetailViewController {
        //configure vc properties here
    }
}