Search code examples
swiftuinavigationcontrolleruibuttoniboutlet

IBOutlet nil - button


I have a HomeController and a registerController. The HomeController is embedded in a navigation controller and is the root view controller. If I present the registerController modally in HomeController's ViewWillAppear:

let reg = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "signup") as! RegisterController
reg.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
reg.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
reg.view.frame = self.view.frame
self.view.addSubview(reg.view)

There is no problem. BUT if I present it by pushing it on the navigation controller stack:

let v = RegisterController()
    self.navigationController?.pushViewController(v, animated: true)

the app crashes and says the IBOutlet for the signUp button (which is in registerController) is nil. I've re-created the outlet and cleaned the project and restarted xcode and nothing has worked...


Solution

  • It’s not a “bug”. Your code is what’s at fault. It has nothing to do with pushing vs presenting. It’s that this line is wrong:

    let v = RegisterController()
    

    That creates a barebones view controller with no outlets hooked up. The outlets are hooked up in the storyboard instance of this class. Create the view controller from the storyboard as you did in the first code, and all will be well.

    let v = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "signup") as! RegisterController