I have a view controller (SecondViewController) with a method named setupHomeScreen that is called from another view controller (FirstViewController). This method is called after SecondViewController is initialized.
Within setupHomeScreen, a UIView is created that I would like to have the same boundaries as the main view, which will depend on whether the iPad is viewed in portrait or landscape mode.
When the method is first called (which is on app startup), the view is completely wrong, and an NSLog output shows the self.view.frame.size.width is equal to 0.0000.
If I navigate to ThirdViewController, and then back to SecondViewController, the view is correctly displayed and the self.view.frame.size.width value is 768.
I have tried a lot of different things to solve this, like putting the contents of the method inside the didRotateFromInterfaceOrientation and viewDidAppear: methods, but nothing seems to work.
Any help would be greatly appreciated.
That’s probably because the view hasn’t been loaded yet. View controllers don’t load their views until they’re actually needed, which is usually when the views are about to be displayed for the first time. If your code is trying to find the view’s width before the view has been displayed, there’s a good chance that the view hasn’t been loaded. In Objective-C you’re allowed to send messages to
nil, and the result will be 0 or nil, depending on the expected type.That’s consistent with the explanation above; once you’ve displayed your
SecondViewControllerview hierarchy, those views will have been loaded, and finding the width of your view is no problem.Simply accessing the view controller’s
viewproperty should be enough to cause the view hierarchy to be loaded. If you must, then, you can fix your problem by accessingself.viewbefore callingsetupHomeScreen. A much better solution, though, is to set your view’s width in the-viewDidLoadmethod ofSecondViewController, which will maintain the view controller’s “lazy loading” behavior (and conserve memory) while still ensuring that your view’s width will be set when it’s needed.