I noticed that when I update my autolayout constraints programmatically, all changes are reverted when I rotate the screen.
Reproduce the issue:
Basic Storyboard interface with UIView and 2 constraints:
- width equal superview.width (multiplier 1) active
- width equal superview.width (multiplier 1/2) disabled
Create and link these 2 constraints with IBOutlet
- Programmatically disable the first constraint and enable the second one.
- Rotate the device, the first constraint is active and the second one disabled.
Seems like a bug to me.
What do you think ?
Screenshots:
Constraint #1:
Constraint #2:
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.
portrait with full width landscape with half width
You can do the necessary switch with the constraints created via IB for size classes. The trick is to keep the collapsed state in a variable and update constraints as on your button's event as also on trait collection change event.
Size Classes
Installed refers to Size Classes installation, not to active/inactive.
You must create another constraint programmatically, and activate/deactivate that one. This is because you cannot change the multiplier of a constraint (Can i change multiplier property for NSLayoutConstraint?), nor can you tinker with Size Classes (activateConstraints: and deactivateConstraints: not persisting after rotation for constraints created in IB).
There are a few ways to do so. In the example below, I create a copy of your x1 constraint, with a multiplier or 1/2. I then toggle between the two:
Tested on iOS 9+, Xcode 7+.