關於ContentCompressionResistance, ContentHugging運用
如下圖效果圖,兩個Label並列在同一排上,左邊label自適應,右邊label(紅色)要使得內容全部展示,如果左邊label內容很少,那麼右邊label隨著左邊label動。
使用Snapkit 約束實現效果
使用xib AutoLayout 約束實現效果xib AutoLayout關鍵設定
1.設定好相關約束,詳見demo.
2.把左邊label Compression horizontal降低至250(預設750,設定低於750任意值均可),右邊紅色label無需修改。
如下圖
Snapkit 約束關鍵程式碼
import UIKit
import SnapKit
class SnpTableViewCell: UITableViewCell {
var placeLabel = UILabel()
var distanceLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
/// MARK: -setup UI
func setupUI() {
distanceLabel.textColor = UIColor.red
if #available(iOS 8.2, *) {
distanceLabel.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
} else {
distanceLabel.font = UIFont.boldSystemFont(ofSize: 17)
}
contentView.addSubview(placeLabel)
contentView.addSubview(distanceLabel)
placeLabel.snp.makeConstraints {
$0.left.equalToSuperview().offset(16)
$0.top.bottom.equalToSuperview()
}
distanceLabel.snp.makeConstraints{
$0.top.bottom.equalToSuperview()
$0.left.equalTo(placeLabel.snp.right).offset(32)
$0.right.lessThanOrEqualToSuperview().offset(-16)
}
//set CompressionResistance ContentHugging
distanceLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
distanceLabel.setContentHuggingPriority(.required, for: .horizontal)
placeLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
placeLabel.setContentHuggingPriority(.required, for: .horizontal)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
複製程式碼
關鍵設定程式碼是:
//set CompressionResistance ContentHugging
distanceLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
distanceLabel.setContentHuggingPriority(.required, for: .horizontal)
placeLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
placeLabel.setContentHuggingPriority(.required, for: .horizontal)
複製程式碼