简体   繁体   English

如何激活先前已停用的约束?

[英]How can I activate, previously deactivated constraint?

I keep references to my NSLayoutConstraint 我保留了对我的NSLayoutConstraint引用

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

Then for some @IBAction I activate/deactivate depending on my flag variable: 然后对于某些@IBAction我根据我的flag变量激活/停用:

@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 . 但是当我再一次调用我的动作时,在myConstrain unexpectedly found nil while unwrapping an Optional value时,我unexpectedly found nil while unwrapping an Optional value了一个错误unexpectedly found nil while unwrapping an Optional value

More over it doesn't animate. 更多的东西没有动画。 What am I doing wrong? 我究竟做错了什么?

I follow tutorial from WWDC 2015: 我按照WWDC 2015的教程:

在此输入图像描述

Deactivating a constraint is same as calling removeConstraint: for a view. 取消激活约束与调用removeConstraint:对于视图相同。 Refer the documentation . 请参阅文档 So when you remove an object which has weak reference will cause the object deallocation for it. 因此,当您删除具有weak引用的对象时,将导致对象取消分配。 Now this object is nil and activating it won't have any effect at all. 现在这个对象是nil并且激活它根本不会有任何影响。 To solve the issue you need to have a strong reference to constraint object. 要解决此问题,您需要对约束对象进行强有力的引用。

@IBOutlet strong var myConstraint: NSLayoutConstraint!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM