根据 UIKit 模块内的 NSLayoutConstraints 类,如果约束的优先级小于 UILayoutPriorityRequired,则它是可选的。高优先级的约束会在低优先级约束之前满足。约束的满足不是全有或全无的。如果约束“a == b”是可选的,这意味着我们将尝试最小化“abs(a-b)”。
此属性只能在初始设置或可选时修改。在将约束添加到视图后,如果将优先级从/到 NSLayoutPriorityRequired 更改,将引发异常。
示例:带有不同优先级的 UIButton 约束。
func setConstraints() {
buttonMessage.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: buttonMessage, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: -10).isActive = true
let leading = NSLayoutConstraint(item: buttonMessage, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 10)
leading.isActive = true
let widthConstraint = NSLayoutConstraint(item: buttonMessage, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
let heightConstraint = NSLayoutConstraint(item: buttonMessage, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
let trailingToSuperView = NSLayoutConstraint(item: buttonMessage, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
trailingToSuperView.priority = 999
trailingToSuperView.isActive = true
buttonMessage.addConstraints([widthConstraint,heightConstraint])
}