Search code examples
iosswiftnslayoutconstraint

How to set two UILabels compression priority to make one push the other vertically?


One image is worth a thousand words:

These two labels are in a UICollectionviewCell. These are the activated constains on the labels:

blue.topAnchor.constraint(equalTo: container.topAnchor)
blue.leftAnchor.constraint(equalTo: container.leftAnchor)
blue.rightAnchor.constraint(equalTo: container.rightAnchor)

green.topAnchor.constraint(equalTo: bottomAnchor)
green.leftAnchor.constraint(equalTo: container.leftAnchor)
green.rightAnchor.constraint(equalTo: container.rightAnchor)
green.bottomAnchor.constraint(equalTo: container.bottomAnchor)

And what I tried to do but doesn't seem to work :

blue.setContentHuggingPriority(.defaultLow, for: .vertical)
blue.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
green.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)

How can I make the blue label to take the least possible space, being pushed by the green one ?

Both labels are multilines.


Solution

  • You need to set the vertical content hugging of green label lower than the vertical content hugging of the blue label.

    Here is an article that always help me when i forget how this works: https://medium.com/@abhimuralidharan/ios-content-hugging-and-content-compression-resistance-priorities-476fb5828ef