I noticed that when I update my autolayout constraints programmatically, all changes are reverted when I rotate the screen.
Reproduce the issue:
Basic S
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.
var collapsed: Bool {
didSet {
view.setNeedsUpdateConstraints()
}
}
@IBAction func onButtonClick(sender: UISwitch) {
view.layoutIfNeeded()
collapsed = !collapsed
UIView.animate(withDuration: 0.3) {
view.layoutIfNeeded()
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
view.setNeedsUpdateConstraints()
}
override func updateViewConstraints() {
constraint1.isActive = !collapsed
constraint2.isActive = collapsed
super.updateViewConstraints()
}