In Swift, it is quite common to see ContentHugging and ContentCompressionResistance either when we are using the storyboard or code to render the user interfaces in UIStackView. Those 2 properties determine how a view can automatically adjust its size with the content give, such as dynamic & long text, images and so on.
π ContentHugging
ContentHugging determines how strongly a view resists increasing its size to fit its content. Which is often used to prevent a view from becoming too large for its content. Let's have a look an example of view within UIStackView:
// don't let label text field stretch at all
label.setContentHuggingPriority(.required, for: .horizontal)
// let label text field stretch if needed
label.setContentHuggingPriority(.defaultHigh, for: .horizontal)
Here, label is an instance of UILable which sits inside a UIStackView.
π ContentCompressionResistance
ContentCompressionResistance determines how strongly a view resists decreasing its size when there is not enough space for it in the user interface. Similarly as above, this property is often used to prevent a view from becoming too small for its content, example:
let myView = UIView()
myView.setContentCompressionResistancePriority(.required, for: .vertical)
In this example, we are creating a new view (inside a UIStackView) and let its ContentCompressionResistance priority for the vertical axis to .required, meaning the myView will resist shrinking along the vertical axis as much as possible, and it will only shrink if there is not enough space in the user interface for it to maintain its original size.
Notice that: Sometimes we need both properties ContentHugging and ContentCompressionResistance in order to render our views properly depends on the situtation.
Summary
The general practise rule is that:
Views that contain text or other important content should have high values for both content hugging and content compression resistance
Views that are less important or that can be resized without affecting the readability of the content can have lower values.
Ref: https://needone.app/contenthugging-and-contentcompressionresistance/
Top comments (0)