首页 > 解决方案 > 如何用故事板呈现课堂

问题描述

我以编程方式编写 UI,现在我想从情节提要中添加 ui,当我尝试这样做时,编译器说“Unexpectedly found nil while unwrapping an Optional value”

在 storyboard -> ViewController -> Custom Class 我设置了我的类。我还设置了 ID "board1" 为什么它设置 nil 值???

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        table.deselectRow(at: indexPath, animated: true)
        let registerViewController = storyboard?.instantiateViewController(withIdentifier: "board1") as? RegisterViewController
        present(registerViewController!, animated: true, completion: nil)
    }

标签: swiftuiviewcontrollerstoryboard

解决方案


您似乎在storyboard这里使用了一些未知的实例:

let registerViewController = storyboard?.instantiateViewController(withIdentifier: "board1") as? RegisterViewController

根据您的评论,您storyboard似乎没有声明。这意味着它可能不是指您的Main.storyboard文件,甚至可能为零。

您应该创建一个UIStoryboard引用您的Main.storyboard文件的新实例,如下所示:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let registerViewController = storyboard.instantiateViewController(withIdentifier: "board1") as? RegisterViewController

推荐阅读