我以编程方式编写UI,现在我想从情节提要中添加ui,当我尝试这样做时,编译器会说“在展开可选值时意外发现nil”
在情节提要中-> ViewController->自定义类我设置了我的类。我也设置了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)
}
答案 0 :(得分:1)
您似乎在此处使用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
答案 1 :(得分:0)
您可以这样做:
// Perform the segue to the viewController you want. Make sure you set the identifier the same as in the storyboard
let VC1 = (self.storyboard?.instantiateViewController(withIdentifier: "yourIdentifier"))!
self.present(VC1, animated: true, completion: nil)
也可以为此编写扩展名:
extension UIViewController {
func presentView(withIdentifier: String) {
if let newVC = self.storyboard?.instantiateViewController(withIdentifier: withIdentifier) {
self.present(newVC, animated: true, completion: nil)
}
}
}
然后这样称呼
self.presentView(withIdentifier: "yourIdentifier")