阅读 806

iOS AutoLayout使用技巧

关于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)
复制代码

关于详细实现过程,及原理待续。。。。

代码地址点击这里

评论