Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I activate, previously deactivated constraint?

I keep references 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 once again, I have an error unexpectedly found nil while unwrapping an Optional value for myConstrain.

More over it doesn't animate. What am I doing wrong?

I follow tutorial from WWDC 2015:

enter image description here

like image 533
Bartłomiej Semańczyk Avatar asked Jul 11 '15 14:07

Bartłomiej Semańczyk


People also ask

How do I enable constraints in Swift?

addConstraint(constY); var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute. Width, relatedBy: NSLayoutRelation. Equal, toItem: new_view, attribute: NSLayoutAttribute. Width, multiplier: 1, constant: 0); self.

How do I turn off constraints?

To turn off geometric constraints: On the command line in AutoCAD, enter CONSTRAINTINFER and set the value to 0 (zero) Enter CONSTRAINTSETTINGS command and on the Geometric tab, uncheck the box for "Infer geometric constraints."

What is NSLayoutConstraint in Swift?

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.


1 Answers

Deactivating a constraint is same as calling removeConstraint: for a view. Refer the documentation. So when you remove an object which has weak reference will cause the object deallocation for it. Now this object is nil and activating it won't have any effect at all. To solve the issue you need to have a strong reference to constraint object.

@IBOutlet strong var myConstraint: NSLayoutConstraint!
like image 186
Gandalf Avatar answered Oct 11 '22 06:10

Gandalf