??這一篇我們分析下使用 SnapKit 在布局時(shí)候的兩個(gè)重要的概念 HuggingPriority-抗拉伸 和 CompressionResistancePriority-抗壓縮。
HuggingPriority-抗拉伸
??在布局的過程中弄诲,我們往往會(huì)遇到兩個(gè) View 放在同一行的情況矢炼,如果兩個(gè) View 不能夠填滿整個(gè)空間,就會(huì)被拉伸瘤礁。
HuggingPriority
??這種情況,我們?cè)O(shè)置左邊抗拉伸強(qiáng)度為Height备绽,這樣在左右兩邊的Label有空隙的時(shí)候券坞,會(huì)拉伸右邊的Label。
leftLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(200)
make.left.equalToSuperview().offset(20)
make.right.greaterThanOrEqualTo(rightLabel.snp.left).offset(-10).priority(.medium)
}
leftLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
rightLabel.snp.makeConstraints { (make) in
make.top.equalTo(leftLabel)
make.left.greaterThanOrEqualTo(leftLabel.snp.right).offset(10).priority(.medium)
make.right.equalToSuperview().offset(-20)
}
CompressionResistancePriority-抗壓縮
??與 HuggingPriority-抗拉伸 相對(duì)應(yīng)的就是 CompressionResistancePriority-壓縮肺素。
![-抗壓縮
??與 HuggingPriority-抗拉伸 相對(duì)應(yīng)的就是 CompressionResistancePriority-壓縮恨锚。
舉個(gè)栗子:
??這中情況下,我們?cè)O(shè)置 LeftLabel 抗壓縮性 CompressionResistancePriority 為 high倍靡,設(shè)置 RightLabel 的 CompressionResistancePriority 為 low猴伶,那么就會(huì)自動(dòng)拉伸 RightLabel,而 LeftLabel 就會(huì)維持原狀。
leftLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(200)
make.left.equalToSuperview().offset(20)
make.right.greaterThanOrEqualTo(rightLabel.snp.left).offset(-10).priority(.high)
}
leftLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
rightLabel.snp.makeConstraints { (make) in
make.top.equalTo(leftLabel)
make.left.greaterThanOrEqualTo(leftLabel.snp.right).offset(10).priority(.medium)
make.right.equalToSuperview().offset(-20)
}
rightLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)