【问题标题】:Why am I unable to install a constraint on my view?为什么我无法在我的视图上安装约束?
【发布时间】:2017-09-25 19:47:00
【问题描述】:

我正在尝试将一个按钮从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 约束时哪里出错了?

【问题讨论】:

  • 按钮的superview和self.view有关系吗?

标签: ios swift nslayoutconstraint uiviewanimation


【解决方案1】:

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

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

self.myButton.addConstraint(newCenterConstraint)

与:

self.view.addConstraint(newCenterConstraint)

不过,正如 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)

【讨论】:

  • 现在说得通了。对此有更简单的捷径,但它们似乎都不是最聪明的解决方案。非常感谢!
【解决方案2】:

我会使用一个带有常量的 centerX 约束来将其偏移到屏幕外。然后动画设置常量为0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2021-10-18
    • 1970-01-01
    • 2016-08-17
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多