【Swift】StoryBoard IDを遷移する時の注意点

どうも、ねこきち(@nekokichi1_yos2)です。

 

StoryBoardIDで遷移する時、下記のコードだとnilが返されて、エラーになります。

let vc = self.storyboard!.instantiateViewController(withIdentifier: "遷移先のStoryBoardID") as! 遷移先
self.present(vc, animated: true, completion: nil)

(オプショナルバインティングでもダメでした。)

 

直接storyboardを指定するのではなく、予めstoryboardを生成しておくと、うまくいきます。

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc = storyboard.instantiateViewController(withIdentifier: "遷移先のStoryBoardID") as! 遷移先
self.present(vc, animated: true, completion: nil)

(参考)

stackoverflow.com