View controllers are responsible for managing a single view hierarchy. The top-level view, containing all of the subviews, is stored in the view property of the view controller.
There are multiple ways to provide a UIViewController with a view:
- In a storyboard, you can design the complete view hierarchies of multiple view controllers, embed controllers, and use advanced features such as segues and transitions. Storyboards can get very complex quickly, and many developers prefer not to use them. For me, though, they are a very powerful tool, to be used with great care.
- From a nib, which lets you define a single UIViewController. Nibs have the advantage of being more lightweight than storyboards, but they are also less powerful, as they don't support controller embedding and references to external nibs.
- Using the loadView() method, and creating the complete view hierarchy programmatically. When using loadView(), it is possible to load the views from many nibs and assemble them together in a unique view hierarchy.
When displaying a view controller on-screen, whether from a modal presentation, inside a navigation controller, or directly from the application's delegate window, methods will be called to help you manage its life cycle. They are as follows:
- viewDidLoad() is called when the view loading has been performed, usually after the first access to the view property
- viewWillAppear(Bool) is called just before the view is added to a view hierarchy
- viewDidAppear(Bool) is called when the view has been added to a view hierarchy
- viewWillDisappear(Bool) is called when the view will be removed from a view hierarchy
- viewDidDisappear(Bool) is called when the view has been removed from a view hierarchy
These methods are called by UIKit. It is recommended that you avoid calling them manually; and when overriding them, you should always call super. Try to ensure that the life cycles of your view controllers fit inside the UIKit flow.
Now, let's have a look at some anti-patterns that you should avoid with UIViewController.