iOS - Where to initialize views
If I want to initialize views programmatically, where in the
viewcontroller lifecycle should this happen?
The initial intuition is loadView. However, here, we don't yet have the
frame of the view itself (necessary for calculating the sizes/positions of
the views). Ditto for viewDidLoad.
Next intuition is viewWillAppear- here we DO (finally) have a guarantee of
the frame of the view. However, this has potential to be called many times
throughout the vc lifecycle. Ditto for viewDidAppear, etc...
Finally, I found viewWillLayoutSubviews. This works for the initialization
of most static layouts- however, whenever any view moves this gets called
again (same problem as viewWillAppear).
I've seen recommendations to init the views in loadView and set their
frames in viewWillLayoutSubviews (since setting frames should be
idempotent, who cares if it gets called a couple times). But then why does
apple so strongly encourage initWithFrame: as the standard initialization
method of UIViews
(https://developer.apple.com/library/ios/documentation/windowsviews/conceptual/viewpg_iphoneos/CreatingViews/CreatingViews.html)?
Would it be crazy to subclass all my UIViewControllers to have an
initWithViewFrame: method? That way I can pass in a frame, manually set it
immediately in loadView and be done with it? Or is it better to have a
viewHasBeenFormatted flag in loadView that, if not set, calls the
formatting of views and then sets it?
Or is this just apple's way of saying "use interface builder or you're
screwed"?
Any help is appreciated!
No comments:
Post a Comment