IBOutlet variables return nil when I try to access them. Error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

只愿长相守 提交于 2019-12-02 13:20:53

From your comments, I understood that you are instantiating the controller wrongly.

let mainController = ViewController(). // Wrong

This will just instantiate the ViewController but not any objects from the story board.

Use below code to instantiate viewcontroller from storyboard.

    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "mainViewController") as? ViewController {
        //Set any data if required, then present
        self.present(vc, animated: true, completion: nil)
    }

If you use multiple storyBoards,

 let storyboard = UIStoryboard(name: "Main", bundle: nil)
 if let vc = storyboard.instantiateViewController(withIdentifier: "mainViewController") as? ViewController {
        self.present(vc, animated: true, completion: nil)
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!