Why weak IBOutlet NSLayoutConstraint turns to nil when I make it inactive? Why weak IBOutlet NSLayoutConstraint turns to nil when I make it inactive? ios ios

Why weak IBOutlet NSLayoutConstraint turns to nil when I make it inactive?


When your outlet is weak, the only strong reference is from the view's constraints property. Deactivating the constraint removes it from that array, so there are no more strong references.


A possible workaround would be to change the constraint priority instead of making it inactive:

@property (nonatomic, weak) IBOutlet NSLayoutConstraint* leftConstraint;(...)self.leftConstraint.priority = 250;

Then, self.leftConstraint is not disposed.

EDIT:

Xcode does not support changing priority for required (=1000) constraints, so be sure you switch in a range between 1...999.


First change the IBOutlet variable to an optional. ie:

from :

@IBOutlet weak var myConstraint : NSLayoutConstraint!

to:

@IBOutlet weak var myConstraint : NSLayoutConstraint?

Now, to make it easier to manage/change from the storyboard in the future, add a new variable (eg myConstraint_DefualtValue) and set this to the value of myConstraint in viewDidLoad

var myConstraint_DefualtValue = CGFloat(0)override func viewDidLoad() {    super.viewDidLoad()    self.myConstraint_DefualtValue = self.myConstraint.constant}

I assume it is obvious why you need to set it in viewDidLoad and not somewhere else

Then when you want to deactivate it:

self.myConstraint?.isActive = false

And when you want to reactivate it (assuming you have the view as an outlet(myViewThatHasTheConstraint) and the constraint is a height constraint):

self.myConstraint = self.myViewThatHasTheConstraint.heightAnchor.constraint(equalToConstant: self.myConstraint_DefualtValue);self.myConstraint?.isActive = true