0

In UIViewControllers I have several methods such as viewDidLoad, viewWillAppear, viewDidAppear, etc. The question is: "what is the best place to, for example, set the background color of my view, instantiate, and set the background color of a UILabel, or instantiate an object that I set as @property in my class and things like that? "

Thanks!

Marco Manzoni
  • 707
  • 3
  • 11
  • 21

3 Answers3

2

So many questions at once!

The first time the view is loaded, in viewDidLoad you will already have access to all the readily initialized UI elements, so it is a great place to configure the view and to set your class properties.

If you come back to the view if it is already loaded (say, by popping a view from a navigation controller, or dismissing a modal view controller), viewDidLoad will not be called. Thus, if you want to change something (background, add a label, change the background of a label, etc.) based on something that might have happened since the view controller was initialized, you have to use viewWillAppear.

You would use viewDidAppear if you want to animate a change so the user can see it after the view has already become visible.

Edit: this is pertinent for if you use IB or storyboard. See CitronEvanescent's answer for the case that you create your view in code.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • Beware, viewWillAppear is called every time the view is displayed, eg. when you pull back the view of a controller after pop-ing another one. Considering your updates and your navigation it can be a bit expensive – CitronEvanescent Nov 01 '12 at 14:16
  • Fair enough. Not for the mentioned things, though. – Mundi Nov 01 '12 at 14:17
0

If you are creating your view programaticaly, you can set your properties on - (void) loadView this method will be call once before anything is displayed.

Generally i prefer instantiating the UI elements in the -(id) init and update their UI in loadView.

For further details : View construction reference

  • Why instantiate in `init` and not in `loadView`? Kinda defeats the purpose of `loadView` imho. – Rengers Nov 01 '12 at 16:53
  • You can do both, that would depends in how you need to handle your objects. Don't forget loadView is called if view has been unloaded (cf. upon memory warning for ios 5 and less) – CitronEvanescent Nov 12 '12 at 14:07
0

The feasible method would be viewDidLoad or -(id)init,-(id)initWithNibName constructors of the class. viewWillAppear and viewDidAppear should be avoided,since you would not like to instantiate your variables again and again since they get called every time the view appears(from pop or tabSwitch).These two methods can be useful in case you want to change some variable values on reappearance

AppleDelegate
  • 4,269
  • 1
  • 20
  • 27