Hello
I set a few constraints on a UIView in the storyboard. The height constraint is set to 300 and has a size class variation set on 350 (see screenshot).
In my code, I modify the constraint and set its constant to 100. When I call that code, I see the view changing correctly its height to 100. But If I go to homescreen ( app in background) and come back to the app, the height of the view is set back to the old value (300). This problem only appears when the constraint has a size variation. When I remove the variation on the height, the behaviour is ok, the height stays at 100 when I go to homeview and switch back to the app. Is that a bug of AutoLayout ? Is there a workaround ?
(tested with iOS16, on iPhone Xr and iPhone 14 Pro, xcode 14)
class ViewController: UIViewController {
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buttonPushed(_ sender: Any) {
heightConstraint.constant = 100; // works ok until app goes background
}
}
That means that we should never modify NSLayoutConstraint.constant in the code... or else save the values and restore them in viewDidLayoutSubviews.
My solution would be to create the troublesome constraint in code and convert the existing storyboard constraint to a design-time placeholder. Then no further workaround is needed.
@IBOutlet var myView: UIView! // btw, ‘weak’ is not usually needed
var heightConstraint: NSLayoutConstraint! // no longer an outlet
override func viewDidLoad() {
super.viewDidLoad()
let h = traitCollection.horizontalSizeClass == .regular ? 350 : 300
heightConstraint = myView.heightAnchor.constraint(equalToConstant: h)
heightConstraint.isActive = true
}