achiral
achiral

Reputation: 601

iOS - self.view.frame.size.width is 0.00000

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.

Upvotes: 2

Views: 1324

Answers (1)

Caleb
Caleb

Reputation: 125037

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.

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.

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.

That's consistent with the explanation above; once you've displayed your SecondViewController view hierarchy, those views will have been loaded, and finding the width of your view is no problem.

Simply accessing the view controller's view property should be enough to cause the view hierarchy to be loaded. If you must, then, you can fix your problem by accessing self.view before calling setupHomeScreen. A much better solution, though, is to set your view's width in the -viewDidLoad method of SecondViewController, 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.

Upvotes: 4

Related Questions