How can I activate a previously deactivated restriction?

I keep links to my NSLayoutConstraint

 var flag = true @IBOutlet weak var myConstraint: NSLayoutConstraint! 

Then for some @IBAction I activate / deactivate depending on my flag variable:

 @IBAction func tapped(sender: UIButton) { flag = !flag UIView.animateWithDuration(1.0) { if self.flag { NSLayoutConstraint.activateConstraints([self. myConstraint]) } else { NSLayoutConstraint.deactivateConstraints([self. myConstraint]) } } } 

But when I call my action again, I have the error unexpectedly found nil while unwrapping an Optional value for myConstrain .

Moreover, it does not revive. What am I doing wrong?

I follow WWDC 2015 guide:

enter image description here

+5
source share
1 answer

Deactivating a constraint is similar to calling removeConstraint: for a view. Consult the documentation . Therefore, when you delete an object that has a weak link, it will free the object. Now this object is nil , and its activation will have no effect. To solve the problem, you need to have a strong reference to the restriction object.

 @IBOutlet strong var myConstraint: NSLayoutConstraint! 
+14
source

All Articles