Reputation: 1037
I don't get it to work and I don't know why... the other questions + answers sadly didn't help.
Tested devices:
iPhone 6
iPad 2
Relevant code:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator){
updateConstraints()
}
override func viewWillLayoutSubview() {
updateConstraints()
}
func updateConstraints() {
if UIDevice.currentDevice().orientation.isLandscape {
NSLayoutConstraint.activateConstraints(layoutLandscape!)
NSLayoutConstraint.deactivateConstraints(layoutPortrait!)
}
else {
NSLayoutConstraint.activateConstraints(layoutPortrait!)
NSLayoutConstraint.deactivateConstraints(layoutLandscape!)
}
view.layoutIfNeeded()
}
layoutLandscape and layoutPortrait being arrays of constraints.
Cases this does work:
- iPad loading the view, portrait and landscape
- iPad rotating the view, portrait and landscape
- iPhone loading the view, portrait and landscape
- iPhone rotating the view, only landscape -> portrait
does not work:
- iPhone portrait -> landscape
The iPhone rotation works this way when I activate the portrait as default in the storyboard. If I change that to the landscape constraints, then portrait -> landscape works and the other one doesn't.
The error message (which is also not really helping...) is just that I break some constraints (which are quite a few, so too hard to narrow it down), but then I wonder why it does work when I load the view in both orientations on iPhone.
And why does it work completely on the iPad? It's not like that thing has a much higher resolution than the iPhone or anything like that.
Thanks :)
Upvotes: 1
Views: 757
Reputation: 78855
When you activate layout constraints, they are immediately checked if they are in conflict with other constraints. If so, some are broken, i.e. removed.
In your code, this can happen because you first activate the constraints, at which point you have too many, conflicting constraints.
So the first approach is to first deactivate the no longer relevant ones and then activate the new ones (instead of the other way round).
Another and supposedly more efficient approach is to not activate and deactivate the constraints, but to set the priority to 999 for the currently relevant ones and to 1 for the irrelevant ones. (Note: It's 999 and not 1000.)
Upvotes: 5