ryanwiesjahn
ryanwiesjahn

Reputation: 273

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

Setup:

I have 2 labels set up like this:

Labels, before autoshrink

Orange Containing View:

Left Label:

Right Label:


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.

Upvotes: 3

Views: 1426

Answers (3)

Gary Hooper
Gary Hooper

Reputation: 342

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.

Upvotes: 2

Ganesh Kamath
Ganesh Kamath

Reputation: 1181

It isn't possible by just using autolayout constraints. One thing you can do is as follows:

  1. Set the Autoshrink to Fixed Font Size for both the labels.

  2. Have two font sizes (minFontSize and maxFontSize) between which it is OK for the texts to be rendered with.

  3. Concatenate both the texts and find the font size (calculatedFontSize) that is needed for the concatenated text to fit the available width. You can refer it here.

To calculate the available width, use the following:
availableWidth = width(orangeView) - leftSpace - rightSpace - betweenSpace

For your instance: leftSpace is 8, rightSpace is 8, betweenSpace is 8.

  1. Your target fontSize, targetFontSize = min(max(calculatedFontSize, minFontSize), maxFontSize)

  2. Now, apply the target font to the two labels.

Upvotes: -1

Jože Ws
Jože Ws

Reputation: 1814

Add left label width equals right label width constraint

Upvotes: 1

Related Questions