SnapKit-进阶篇

作者: 胖子程 | 来源:发表于2018-06-24 22:39 被阅读200次

      这一篇我们分析下使用 SnapKit 在布局时候的两个重要的概念 HuggingPriority-抗拉伸 和 CompressionResistancePriority-抗压缩。

    HuggingPriority-抗拉伸

      在布局的过程中,我们往往会遇到两个 View 放在同一行的情况,如果两个 View 不能够填满整个空间,就会被拉伸。

      这时我们设置其中不需要拉伸的 View 的 HuggingPriority 为 high,就可以让其不被拉伸。举个栗子: HuggingPriority
      这种情况,我们设置左边抗拉伸强度为Height,这样在左右两边的Label有空隙的时候,会拉伸右边的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-抗拉伸 相对应的就是 CompressionResistancePriority-压缩。
    ![-抗压缩
      与 HuggingPriority-抗拉伸 相对应的就是 CompressionResistancePriority-压缩。
    举个栗子:



      这中情况下,我们设置 LeftLabel 抗压缩性 CompressionResistancePriority 为 high,设置 RightLabel 的 CompressionResistancePriority 为 low,那么就会自动拉伸 RightLabel,而 LeftLabel 就会维持原状。

    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)
    

    参考:
    HuggingPriority和CompressionResistance 一个例子教你理解

    相关文章

      网友评论

        本文标题:SnapKit-进阶篇

        本文链接:https://www.haomeiwen.com/subject/ifssyftx.html