All IBOutlets are nil

99封情书 提交于 2019-11-29 12:02:10

I assume you're looking at the outlets immediately after instantiating the scene (you'll also see this behavior if using segues and trying to use the outlets in prepareForSegue). But the outlets are not hooked up until after you present/push to that scene, the view is loaded, and viewDidLoad is called.

Bottom line, do not try to use the outlets prior to viewDidLoad being called (i.e. do not use outlets immediately after instantiating the scene). Instead, pass the needed data to the destination scene (e.g. a String property), and the viewDidLoad of the destination should then populate the outlet.

For example, you might have a property in AboutUsViewController:

var message: String!

When you instantiate AboutUsViewController, you'd set that property:

let aboutUsViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AboutUsViewController") as AboutUsViewController // use `as!` in Swift 1.2

aboutUsViewController.message = "some message"

presentViewController(aboutUsViewController, animated: true, completion: nil)

And then the viewDidLoad of AboutUsViewController would use that property to populate the outlet accordingly:

override func viewDidLoad() {
    super.viewDidLoad()

    label1.text = message
}

But you would never have the originating view controller try to set/adjust the outlets of the destination scene. That's the responsibility of AboutUsViewController.


Just to confirm, are your outlets hooked up properly? The below shows two ways to confirm that they are hooked up properly.

When you select the view controller in Interface Builder and then look in the connections inspector, do you see your outlets hooked up there? In the following snapshot, label1 is hooked up, but label2 is not:

Or when you look at your code, and look at the outlets, do you see solid dots in the left margin (meaning the outlet is hooked up) or empty dots (meaning the outlet is not hooked up)?

You can use this function before presenting, which is available on iOS9 and later:

    aboutUsViewController.loadViewIfNeeded()

I found the answer. Instead of creating UIViewController , I created UIPageViewController!!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!