setNeedsUPdateConstraints 和 setNeedsLayout是两个不同的方法,分别触发AutoLayout的约束更新和视图布局更新。
setNeedsUPdateConstraints 用于通知系统重新计算约束,会触发 updateConstraints 方法,如果想修改约束可以在此函数进行,例如:
class CustomView: UIView {
var someCondition: Bool = false {
didSet {
setNeedsUpdateConstraints()
}
}
override func updateConstraints() {
if someCondition {
// Update constraints based on someCondition
}
super.updateConstraints()
}
}
所以一定不要在updateConstraints中调用 setNeedsUPdateConstraints
setNeedsLayout 用于通知系统需要重新布局视图层次结构标记视图需要更新布局,但不会立即执行,下一个循环触发 layoutSubviews 方法,重新计算和设置视图的frame, 例如:
class CustomView: UIView {
var someCondition: Bool = false {
didSet {
setNeedsLayout()
}
}
override func layoutSubviews() {
super.layoutSubviews()
if someCondition {
// Layout subviews based on someCondition
}
}
}
layoutIfNeeded 用户强制立即布局视图层次结构,而不是等下一个runloop循环,会立即调用layoutsubviews方法,如果视图没有标记为更新,不会执行任何操作