I have designed a view containing two labels. The title text is variable and it should look good for short and long titles, so it is set up to support multiple lines of text (numberOfLines
is 0
) until there is no more room available, at which point the font should shrink (adjustsFontSizeToFitWidth
is true
).
To demonstrate my issue I am using constant title text and adjusting the height of the container instead.
- Things look as expected when the height of the container is sufficient for both labels.
- As soon as the height isn't sufficient, instead of shrinking the title label's font, the subtitle is clipped.
- We prevent this via
subtitleLabel.setContentCompressionResistancePriority(.required, for: .vertical)
. Things look better. The subtitle label is restored to the correct height and the title label's font is reduced instead.
- Let's reduce the height again. The subtitle label looks good still. The title label again adjusts its font, but there is a large amount of top and bottom padding. This makes some sense - there isn't enough height for three lines of title anymore, so the font size shrinks until it fits into two. But we want the label itself to reduce its height to hug the content rather than stranding the title in an ocean of space.
Expected Layout
Things I have tried:
- Let's try to encourage it to do that using
titleLabel.setContentHuggingPriority(.required, for: .vertical)
. No change unfortunately. - Let's remove that line and try something else. We've read that we should try lowering the content compression priority on the title label:
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
. No change. - Another suggestion is to set a minimum scale factor on the title label. Let's try
titleLabel.minimumScaleFactor = 0.5
. No change. - Perhaps we should set a width constraint, even though we are already pinning to the superview? No change.
- A few places suggest setting the label's
preferredMaxLayoutWidth
to match the label's width, but this also doesn't help.
Are there any other suggestions? Is there a way to accomplish this design using autolayout?