Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

SnapKit should be used by most people, probably most people, including me, before they did not understand the use of SnapKit anti-stretching, anti-compression properties, today we have a look at how to use.

HuggingPriority – tensile

In our usual development often encounter this situation, there are two views in the same row, if the two views can not fill the whole space, the general approach is to fix the length of one View, stretch the other View, if not fixed the length of a View, we can not determine which View will be stretched. In this case, we set HuggingPriority of the View, which does not need to be stretched, to high to prevent it from being stretched. API:func setContentHuggingPriority( _ priority: UILayoutPriority, for axis: Axis), the first parameter is priority, and the second parameter is horizontal or vertical

In this case, we can set the tensile strength of the left Label to defaultHigh, so that the right Label will be stretched when there is a gap between the left and right labels. The implementation code is as follows:

leftLabel.snp.makeConstraints { make **in**

    make.top.equalToSuperview().offset(200)

    make.left.equalToSuperview().offset(20)

    make.right.equalTo(rightLabel.snp.left).offset(-10).priority(.medium)

}

leftLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)

rightLabel.snp.makeConstraints { make **in**

    make.top.equalTo(leftLabel)

    make.left.equalTo(leftLabel.snp.right).offset(10).priority(.medium)

    make.right.equalToSuperview().offset(-20)

}
Copy the code
CompressionResistancePriority – compression

And corresponding HuggingPriority – tensile is CompressionResistancePriority – resistance to compression. API for func setContentCompressionResistancePriority (_ priority: UILayoutPriority, for axis: Axis), the first parameter is priority, and the second parameter is horizontal or vertical. As shown in the figure below

As shown in the figure above, among the two labels, the text of the right label is too long. If the length of a certain Lable is not limited in the layout, one of the labels will be compressed. If we set compression properties of the leftLabel CompressionResistancePriority is high, set rightLabel CompressionResistancePriority to low, The RightLabel will be automatically stretched and the leftLabel will remain intact. The implementation code is as follows

leftLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)

rightLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
Copy the code

This allows you to automatically stretch or compress views without limiting the width of a particular View.