When the size of a view controller’s view changes, its subviews are repositioned to fit the new space available to them. The views in the controller’s view hierarchy perform most of this work themselves through the use of layout constraints and autoresizing masks. However, the view controller is also called at various points so that it can participate in the process. Here’s what happens:
- The view controller’s view is resized to the new size.
- If autolayout is not in use, the views are resized according to their autoresizing masks.
- The view controller’s viewWillLayoutSubviews method is called.
- The view’s layoutSubviews method is called. If autolayout is used to configure the view hierarchy, it updates the layout constraints by executing the following steps:
- The view controller’s updateViewConstraints method is called.
- The UIViewController class’s implementation of the updateViewConstraints method calls the view’s updateConstraints method.
- After the layout constraints are updated, a new layout is calculated and the views are repositioned.
Ideally, the views themselves perform all of the necessary work to reposition themselves, without requiring the view controller to participate in the process at all. Often, you can configure the layout entirely within Interface Builder. However, if the view controller adds and removes views dynamically, a static layout in Interface Builder may not be possible. In this case, the view controller is a good place to control the process, because often the views themselves only have a limited picture of the other views in the scene. Here are the best approaches to this in your view controller:
- Use layout constraints to automatically position the views (iOS 6 and later). You overrideupdateViewConstraints to add any necessary layout constraints not already configured by the views. Your implementation of this method must call [super updateViewConstraints].For more information on layout constraints, see Auto Layout Guide.
- Use a combination of autoresizing masks and code to manually position the views (iOS 5.x). You overridelayoutSubviews and use it to reposition any views whose positions cannot be set automatically through the use of resizing masks.For more information on the autoresizing properties of views and how they affect the view, see View Programming Guide for iOS.