iOS AutoLayout使用技巧

關於ContentCompressionResistance, ContentHugging運用

以下圖效果圖,兩個Label並列在同一排上,左邊label自適應,右邊label(紅色)要使得內容所有展現,若是左邊label內容不多,那麼右邊label隨着左邊label動。

使用Snapkit 約束實現效果 git

使用xib AutoLayout 約束實現效果

xib AutoLayout關鍵設置github

1.設置好相關約束,詳見demo.bash

2.把左邊label Compression horizontal下降至250(默認750,設置低於750任意值都可),右邊紅色label無需修改。less

以下圖 ide

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
    }
    
}
複製代碼

關鍵設置代碼是:ui

//set CompressionResistance  ContentHugging
        distanceLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        distanceLabel.setContentHuggingPriority(.required, for: .horizontal)
        
        placeLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        placeLabel.setContentHuggingPriority(.required, for: .horizontal)
複製代碼

關於詳細實現過程,及原理待續。。。。

代碼地址點擊這裏

相關文章
相關標籤/搜索