iOS-Swift-setContentCompressionResistancePriority与setContentHuggingPri
两个UILabel放在同一行,需要设置它们的抗压缩和抗拉伸属性。
class MyView: UIView {
lazy var leftLabel = UILabel()
lazy var rightLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .lightGray
leftLabel.text = "左边的文案"
leftLabel.textColor = .red
leftLabel.backgroundColor = .red.withAlphaComponent(0.2)
rightLabel.text = "右边的文案"
rightLabel.textColor = .blue
rightLabel.backgroundColor = .blue.withAlphaComponent(0.2)
leftLabel.addTo(self).snp.makeConstraints { make in
make.left.equalToSuperview()
make.centerY.equalToSuperview()
}
rightLabel.addTo(self).snp.makeConstraints { make in
make.left.equalTo(leftLabel.snp.right)
make.right.equalToSuperview()
make.centerY.equalToSuperview()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
短文字情况:默认拉伸左边
短文字、左边抗拉伸属性设置为高:拉伸右边
leftLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
文字超长:默认压缩右边
文字超长、左边抗压缩属性设置为低:压缩左边
leftLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
总结
- setContentHuggingPriority是抗拉伸属性,属性低更容易被拉伸,被拉伸是指控件的宽度超过文字宽度,用空白填充
- setContentCompressionResistancePriority是抗压缩属性,属性低更容易被压缩,被压缩是指控件的宽度不足以放下文字,用省略号...代替
- 同一个控件的拉伸和压缩是两个独立的属性,可以同时设置setContentHuggingPriority与setContentCompressionResistancePriority,互不冲突
- 基于布局先放左边文字的情况,默认拉伸左边、压缩右边。也就是默认左边的抗拉伸属性更低,右边的拉压缩属性更低