I am developing an application which supports portrait and landscape modes
. I am using auto layout to arrange my views
. As i have been reading many posts and i have realized that developers commonly use one among the following approaches.
1. First approach:
Implement the UIViewController:updateConstraints
method and update constraints according to device orientation.
2. Second approach:
Implement the UIViewController:viewWillLayoutSubviews
method and update constraints according to device orientation.
Could anyone please tell me what is the best approach to use ? I have been searching for a best practice to combine autorotation and auto layout and nothing yet. Thanks.
The best approach is to use neither. Instead, configure your constraints correctly so that no programmatic changes are required on rotation. The Auto Layout runtime will maintain the views in position as you already have specified.
Updating constraints other than changing the value of
.constant
is a real performance hit and should be avoided.Using
viewWillLayoutSubviews
is not necessary. Auto Layout methods areupdateViewConstraints
(for the view controller), andupdateConstraints
(in the views).I believe that the best approach is to update the constraints in
-(void)updateViewConstraints
by checking the device orientation. There is no need to callsetNeedsUpdateConstraints
inwillAnimateRotationToInterfaceOrientation
because it is automatically called by the iOs when the device orientation changes. Thank you all for the great effort.I would use this UIViewController's method:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
that is called upon rotation, and call
-setNeedsUpdateConstraints
from there. If you need to do additional calculations or manage the contrainsts addfor ios8+
From the documentation for: