UIKit什么时候自动移除约束

When does UIKit remove constraints automatically

在我的 updateLayoutConstraints 中,我正在添加约束,然后调用 super.updateLayoutConstraints()。根据 Apple 文档,这似乎没问题,但是 UIKit remove constraints automatically before calling this function?

我发现这工作正常,但我担心我只是重新添加相同类型的约束。

UIKit 何时自动或不自动移除约束?

updateConstraints 不会删除您添加的任何约束。如果你想避免添加重复的约束,你需要设置一个标志或保留对你已经创建的约束的引用。

约束用于布局用户界面元素,因此在正常情况下不会被删除。

以下是自动删除约束或约束求解器不满足约束的几种情况:

  • 当约束附加到的所有视图都被删除时
  • 如果有冲突约束,但是你会看到这样的错误

    Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

我一般在视图初始化的时候加上约束,比如:

  • viewDidLoadUIViewController
  • init of UIView 那是子类并且没有故事板 xib
  • awakeFromNib of UIView 那是子类并且有故事板