うちのいぬ Tech Blog

Tech Blog of Uchinoinu/My dog

How to handle Error: IBOutlet is nil in ViewController transited by code not by Segue.

Japanese version is here uchinoinu.hatenablog.jp

Env

Situation

  • Make UI using Storyboard
  • Using IBOutlet
  • Transition by Code

Problem

  • 遷移先でIBOutletさんがnilになります

Reason

I did wrong way to call ViewController to transit to.

let nextVC = NextViewController() // This is bad way
navigationController?.pushViewController(nextVC as UIViewController, animated: true)

In above, NextViewController is just called.

In other words, just made instance without Storyboard context information.

So NextViewController has no IBOutlet information.

This is why IBOutlet is nil.

How to overcome

**You should make instance with Storyboard context.

So use StoryboardID.**

let nextVC = storyboard?.instantiateViewController(withIdentifier: Const.StoryboardID.nextViewController) as! NextViewController
navigationController?.pushViewController(nextVC as UIViewController, animated: true)

Now IBOutlet is not nil

References

stackoverflow.com stackoverflow.com stackoverflow.com