2017-09-25 122 views
1

我正在试图从我的UIViewController的可见边界以外的一个按钮动画到它的中心。我的故事板中有一个约束设置,名为myButtonLeading,我将其作为动画的一部分删除,然后我想添加一个名为newCenterConstraint的新约束。为什么我无法在我的视图上安装约束?

@IBAction func updateDidTouch(_ sender: Any) { 

    UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { 

     let newCenterConstraint = NSLayoutConstraint(item: self.myButton, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0) 

     self.myButton.removeConstraint(self.myButtonLeading) 
     self.myButton.addConstraint(newCenterConstraint) 

     self.view.layoutIfNeeded() 

    }, completion: nil) 
} 

我已经把现在是给我关于我自己参考toItem: view以下错误消息的代码。

在闭包中隐式使用'self';使用'自我'。使捕获 语义明确

但是,当我用我的self.view应用程序崩溃与错误消息说:

无法在视图安装约束。该约束是否参考 来自视图子树之外的东西?这是违法的。

我在哪里错在这里添加新的centerX约束?

+0

是按钮的上海华以self.view有关? – CZ54

回答

3

错误非常明显。您正在将self.view的约束添加到self.view的子视图中。

为了解决这个问题替换此行:

self.myButton.addConstraint(newCenterConstraint) 

有了:

self.view.addConstraint(newCenterConstraint) 

更好的办法虽然,娄佛朗哥的建议,是的,而不是动画增加一个新的约束,改变中心x约束的常量并动画layoutIfNeeded函数。 (对于这个你必须为连接的中心x约束的出口。)

它应该是这样的:

UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { 
    self.centerConstraint.constant = 0 
    self.view.layoutIfNeeded() 
}, completion: nil) 
+0

现在非常有意义。这个简单的捷径,但他们都不是最聪明的解决方案。非常感谢! –

0

我只是用一个常数的centerX约束来将它偏移到屏幕外。然后动画设置常数为0.

相关问题