intrinsicContentSize详解
对于UILabel, UIimageView,UIButton等控件都有intrinsicContentSize的特点
- intrinsic Content Size: 固有内部巨细,拥有此特点的控件在设置束缚时,假如没有设置控件的巨细,就会根据此特点来设置控件的巨细
在水平/垂直并行布局中,两个控件的intrinsicSize(固有巨细)比父控件的宽/高的数值大,父控件就没有办法彻底展示完成,就只能经过紧缩其间一个控件来实现。假如咱们想要想要指定某个控件来进行自适应,紧缩另外一个控件,就需要修改控件的束缚优先级,以下两个方法修改优先级
-
setContentCompressionResistancePriority(抗紧缩)
- 数值越低,在宽/高度不够下,就会被紧缩
- 常见默认值:UILayoutPriority.defaultHigh = 750
open func setContentCompressionResistancePriority(_ priority: UILayoutPriority, for axis: NSLayoutConstraint.Axis)
open func setContentHuggingPriority(_ priority: UILayoutPriority, for axis: NSLayoutConstraint.Axis)
使用场景:
-
contentCompressionResistancePriority (抗紧缩)
lazy var label1: UILabel = { let label = UILabel() label.text = "可能会显现省略号的label1" return label }() lazy var label2: UILabel = { let label = UILabel() label.text = "优先自适应的宽度的label2" return label }() view.addSubview(label1) view.addSubview(label2) label1.snp.makeConstraints { make in make.left.top.bottom.equalTo(0) } label2.snp.makeConstraints { make in make.right.top.bottom.equalTo(0) make.left.equalTo(self.label1.snp.right).offset(5) }
- 依照上面的代码显现会label1正常显现,label2被紧缩,假如需求是确保label2正常显现,需要调用setContentCompressionResistancePriority 设置束缚优先级
label1.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) label2.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
-
contentHuggingPriority(抗拉伸)
lazy var label1: UILabel = { let label = UILabel() label.text = "label1" return label }() lazy var label2: UILabel = { let label = UILabel() label.text = "被拉伸的label2" return label }() view.addSubview(label1) view.addSubview(label2) label1.snp.makeConstraints { make in make.left.top.bottom.equalTo(0) } label2.snp.makeConstraints { make in make.right.top.bottom.equalTo(0) make.left.equalTo(self.label1.snp.right).offset(5) }
- 依照上面的代码显现会label1会被拉伸,label2正常显现,假如需求是label1正常显现,拉伸label2,需要调用setContentHuggingPriority 设置束缚优先级
label1.setContentHuggingPriority(.defaultHigh, for: .horizontal) label2.setContentHuggingPriority(.defaultLow, for: .horizontal)