Why am I unable to install a constraint on my view?

Aus*_*nyi 3 uiviewanimation ios nslayoutconstraint swift

I am trying to animate a button from outside the visible bounds of my UIViewController to the center of it. I have a constraint setup in my storyboard called myButtonLeading which I remove as part of my animation, and then I want to add a new constraint called 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)
}
Run Code Online (Sandbox Code Playgroud)

The code I have right now is giving me the following error message regarding my reference to toItem: view.

Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit

But when I used self.view my app crashes with an error message saying:

Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal.

Where am I going wrong here in adding the new centerX constraint?

Pra*_*tti 8

错误非常明显。您正在添加一个引用self.view到 的子视图的约束self.view

要解决此问题,请替换此行:

self.myButton.addConstraint(newCenterConstraint)
Run Code Online (Sandbox Code Playgroud)

和:

self.view.addConstraint(newCenterConstraint)
Run Code Online (Sandbox Code Playgroud)

不过,正如 Lou Franco 所建议的,更好的方法是改变中心 x 约束的常数并为layoutIfNeeded函数设置动画,而不是为添加新约束设置动画。(为此,您必须为中心 x 约束连接一个出口。)

它看起来像这样:

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