根据NSLayoutConstraints class
里面 UIKit Module
如果约束的优先级小于UILayoutPriorityRequired,则它是可选的。在较低优先级约束之前先满足较高优先级约束。约束满足不是全部或全部。如果约束'a == b'是可选的,则意味着我们将尝试最小化'abs(ab)'。只能在初始设置中或在可选时修改此属性。将约束添加到视图后,如果优先级从NSLayoutPriorityRequired更改为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])
}