我想实现一个功能,当我点击按钮时,图像将在两个按钮之间移动
我在图像和button2之间设置了一个约束(centerX,带有222的文本)同时我也用button1设置约束(centerX,带有11的文本)并用950设置优先级然后我将它们拖到viewcontroller
这是我的故事板中的约束
这是我控制约束的代码
if NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1 {
self.kidLeftCenterConstrait.active = isLeft
self.kidRightCenterConstrait.active = !isLeft
UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
self.view.layoutIfNeeded()
})
} else {
let constraintToRemove = isLeft ? self.kidRightCenterConstrait : self.kidLeftCenterConstrait
let constriaintToUse = isLeft ? self.kidLeftCenterConstrait : self.kidRightCenterConstrait
self.douBi.superview!.removeConstraint(constraintToRemove)
self.douBi.superview!.removeConstraint(constriaintToUse)
self.douBi.superview!.addConstraint(constriaintToUse)
UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
在iphone中运行之后
我点击按钮1图像移动到11,然后我点击按钮2,应用程序是现金self.kidRightCenterConstrait.active = !isLeft
控制台日志为fatal error:unexpectedly found nil while unwrapping an Optional value
答案 0 :(得分:31)
似乎约束被释放。您可能会尝试强烈保留约束:
@IBOutlet var kidLeftCenterConstrait: NSLayoutConstraint!
@IBOutlet var kidRightCenterConstrait: NSLayoutConstraint!
无论如何要小心可能的保留周期。检查你的ViewController是否会在它到来的时候消失。
我通常使用这种动画来管理所有代码中的约束。