(iOS) Simultaneously auto-shrink 2 labels that have constraints to each other

Viewed 1241

Setup:

I have 2 labels set up like this:

Labels, before autoshrink

Orange Containing View:

  • Fixed width and height

Left Label:

  • Top, left, and bottom constraints == 8 to Orange View
  • Right constraint >= 8 to Right Label
  • Horizontal Content Hugging is unchanged (251)
  • Horizontal Compression Resistance is unchanged (750)
  • Auto-shrink font to minimum scale of 0.5

Right Label:

  • Top, right, and bottom constraints == 8 to Orange View
  • Left constraint >= 8 to Left Label
  • Horizontal Content Hugging is unchanged (251)
  • Horizontal Compression Resistance is unchanged (750)
  • Auto-shrink font to minimum scale of 0.5

What I want to happen:

When the label texts become longer, BOTH labels' fonts shrink together to a minimum font scale (or size) before truncating.


What's actually happening:

Only 1 label's font auto-shrinks and then truncates, and I get a constraint complaint about needing to make 1 of the label's Compression Resistance higher than the other. Even when satisfying that constraint, both labels' fonts won't auto-shrink.

Labels, after autoshrink


Question:

Is there any way, through autolayout or code, to get both of the labels' fonts to first shrink, and then both truncate if needed? Thanks.

3 Answers

Using Xcode 9.2 autolayout, this works automatically for me.

I have the two labels in a view. This view is constrained to a UITableViewCell.

Left Label:

  • leftLabel.top = top
  • leftLabel.leading = leading
  • leftLabel.bottom = bottom
  • rightLabel.trailing = leftLabel.trailing + 8
  • leftLabel hugging priority = ( 251, 251 )
  • leftLabel compression resistance priority = ( 750, 750 )
  • font is size 20, autoshrink set to minimum font size of 12
  • number of lines for label = 1

Right Label:

  • rightLabel.trailing = leftLabel.trailing + 8
  • rightLabel.top = top
  • rightLabel.trailing = trailing
  • rightLabel.bottom = bottom
  • rightLabel hugging priority = ( 252, 251 )
  • rightLabel compression resistance priority = ( 750, 750 )
  • font is size 20, autoshrink set to minimum font size of 12
  • number of lines for label = 1

When the text strings for labelLeft and labelRight are short, the space between them is large. When those strings are long, the space between them is small (nearly exactly 8) and both fonts have shrunk, equally.

Related