關于ContentCompressionResistance, ContentHugging運用
如下圖效果圖,兩個Label并列在同一排上,左邊label自適應,右邊label(紅色)要使得內容全部展示,如果左邊label內容很少,那么右邊label隨著左邊label動。
使用Snapkit 約束實現效果
xib AutoLayout關鍵設置
1.設置好相關約束,詳見demo.
2.把左邊label Compression horizontal降低至250(默認750,設置低于750任意值均可),右邊紅色label無需修改。
如下圖
Snapkit 約束關鍵代碼
import UIKit
import SnapKitclass 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 UIfunc setupUI() {distanceLabel.textColor = UIColor.redif #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 ContentHuggingdistanceLabel.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 ContentHuggingdistanceLabel.setContentCompressionResistancePriority(.required, for: .horizontal)distanceLabel.setContentHuggingPriority(.required, for: .horizontal)placeLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)placeLabel.setContentHuggingPriority(.required, for: .horizontal)
復制代碼