I will describe how to simple switch between the two layouts.
When the screen rotates, Autolayout apply the installed default layout with the higher priority.
It does not matter whether Constraint is Active or not. Because, when rotating, the high priority layout on the storyboard is reinstalled and active = true.
Therefore, even if you change active, the default layout is applied when you rotate and you can not keep any layout.
Instead of switching active state, switching two layouts.
When switching between two layouts, use "priority" rather than "active".
This way does not need to worry about the state of active.
It's very simple.
First, create two layouts to switch, on Storyboard. Check both for Installed.
A conflict error occurs because two layouts have priority = 1000 (required).
Set the priority of the layout to be displayed first to High. And the priority of the other layout is set to Low, conflict error will be resolved.
Associate constraints of those layouts as IBOutlet of class.
Finally, just switch the priority between high and low at the timing you want to change the layout.
Note, please do not change priority to "required". Layout with priority set to required can not be changed it after that.
class RootViewController: UIViewController {
@IBOutlet var widthEqualToSuperView: NSLayoutConstraint!
@IBOutlet var halfWidthOfSuperview: NSLayoutConstraint!
override func viewDidLayoutSubviews() {
changeWidth()
}
func changeWidth() {
let orientation = UIApplication.shared.statusBarOrientation
if (orientation == .portrait || orientation == .portraitUpsideDown) {
widthEqualToSuperView.priority = UILayoutPriorityDefaultHigh;
halfWidthOfSuperview.priority = UILayoutPriorityDefaultLow;
}
else {
widthEqualToSuperView.priority = UILayoutPriorityDefaultLow;
halfWidthOfSuperview.priority = UILayoutPriorityDefaultHigh;
}
}
}
portrait with full width
landscape with half width
