Reputation: 1442
I have stuck with an issue of Autolayout constraints based on screen orientation. For implementing constraints I use Autolayout anchors, override of traitCollectionDidChange
method and create two function where I setup constraints. Something like that:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
case (.compact, .compact):
print("compact-compact")
setupLandscapeLayout()
case (.compact, .regular):
print("compact-regular")
setupPortraitLayout()
default: break
}
}
private func setupPortraitLayout() {
myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
private func setupLandscapeLayout() {
myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 20).isActive = true
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = false
}
So the problem here is constraints which work only one time during change of orientation. Every next try it doesn't work. I also tried to use view.layoutIfNeeded()
and it didn't help. And even tried to set isActive=false
and create a new constraint - also unsuccessfully(
So is it possible to set constraints in the way I do or there is another better way how to update constraints for screen orientation programmatically?
Upvotes: 0
Views: 224
Reputation: 100503
Currently you're duplicating constraints and this makes conflicts so
Put these 2 constraints in viewDidLoad
(set bot to 20 or -20 according to current orientation )
botCon = myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20)
botCon.isActive = true
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
//
private func setupPortraitLayout() {
self.botCon.constant = -20
self.view.layoutIfNeeded()
}
private func setupLandscapeLayout() {
self.botCon.constant = 20
self.view.layoutIfNeeded()
}
Upvotes: 1