我想实现一个功能,当我单击按钮时,图像将在两个按钮之间移动
我在图像和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,应用程序是现金自我.kidRightCenterConstrait.active =!isLeft
控制台日志是致命错误:在展开Optional值时意外发现nil
解决方法
似乎约束被释放了.您可能会尝试强烈保留约束:
@IBOutlet var kidLeftCenterConstrait: NSLayoutConstraint! @IBOutlet var kidRightCenterConstrait: NSLayoutConstraint!
无论如何要小心可能的保留周期.检查ViewController是否会在到时之前消失.
我通常会在代码中使用这种动画来管理所涉及的约束.