Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does iOS remove inactive constraints

Tags:

ios

autolayout

I noticed that in some cases after I set isActive = false on a constraint in Swift that when I try to access it later it is nil, but this is not always the case. In one situation I had two view controllers, and both set isActive to false on a constraint in viewWillAppear, but in the one view the constraint was available later, and I could set isActive = true and in the other it was nil.

What would cause this behavior? I was able to get around it by setting priority to either 1 or 900 instead, but it still leaves the question of what is really happening in the background.

like image 583
Steve Glick Avatar asked May 30 '26 12:05

Steve Glick


1 Answers

isActive is not a very good property name. The constraint is not actually deactivated, it is removed from the view hierarchy.

If the view had the only weak reference to the constraint, the constraint will be deallocated and you won't be able to activate it again.

That means that if you want the constraint to be kept in memory, you have to reference it strongly, e.g.:

@IBOutlet var myConstraint: NSLayoutConstraint!

not

@IBOutlet weak var myConstraint: NSLayoutConstraint?

If you keep a strong reference, the reference will never get set to nil unless you set it to nil yourself.

like image 159
Sulthan Avatar answered Jun 02 '26 02:06

Sulthan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!