wrong frame size in viewDidLoad

Oleg picture Oleg · Dec 27, 2012 · Viewed 32.1k times · Source

Possible Duplicate:
Why am I having to manually set my view’s frame in viewDidLoad?

I have universal app for iphone and ipad, two storyboards, if I run my app on the iphone simulator in viewDidLoad every frame of each element in nib is correct. But if I do it for ipad (simulator) in frame is nil, but the screen looks correct. Could you please advise me smth? Thanks.

Answer

foundry picture foundry · Dec 28, 2012

It's a very similar question to ios setContentOffset not working on iPad ... And my answer is the same as there:

"You should not initialise UI geometry-related things in viewDidLoad, because the geometry of your view is not set at this point and the results will be unpredictable.

... viewWillAppear: is the correct place to do these things, at this point the geometry is set so getting and setting geometry-related properties makes sense."

This also applies to getting geometry-related properties. Don't get distracted by it's behaving correctly in one circumstance and not in another... The main point is that setting/getting geometry properties too early will yield unpredictable results.

Your screen looks correct because you are seeing the results after viewWillAppear: / viewDidAppear:.

update (ios6)

When using autolayout in ios6, frames are not set until subviews have been laid out. The right place to get frame data under these conditions is in the viewController method viewDidLayoutSubviews.

This is called after viewWillAppear:. But take care - they are not always called together. For example, viewDidLayoutSubviews is called after a rotation, viewWillAppear: is not. viewWillAppear: is called every time a view becomes the visible view*, viewDidLayoutSubviews not necessarily (only if the views needed relaying out).

(* unless the app was backgrounded and is becoming the foreground app, then viewWillAppear: is not called)