1

I am using a UILabel in a UITableViewCell to display a title. Normally the text is not too long and therefore the font size can be large. Notice how the text fills the height of theUILabel like normal.

enter image description here

However, when there is a larger title, I want the UILabel height to reduce to accommodate the smaller font size and not leave a blank gap in its place. Currently, my configuration produces this effect.

enter image description here

I am using constraints in my storyboard and have deliberately not set a fixed height constraint. Here are the relevant constraints added:

enter image description here

I may have made a rookie error in my configuration as I can't remember this effect happening before, but it is giving me real headaches (and a bad looking UI).

Krunal
  • 77,632
  • 48
  • 245
  • 261
Alexander MacLeod
  • 2,026
  • 3
  • 14
  • 22
  • Depending on the other constraints on the other subviews, you could adjust the vertical content hugging priority. Increase it on the label. – jervine10 Oct 10 '17 at 16:01
  • @jervine10 The title label has the highest vertical content hugging priority over any other subviews. – Alexander MacLeod Oct 10 '17 at 16:07

3 Answers3

0

Remove either the Top Space or Bottom Space constraints (depending on where you want the label to be anchored).

This will cause the label to automatically use fit itself to the text size.

Paolo
  • 3,825
  • 4
  • 25
  • 41
  • But then how would my table view know the height of which to display the row at? – Alexander MacLeod Oct 10 '17 at 15:57
  • You can either set the `rowHeight` in code or Interface Builder. If you need a different row height for each row depending on the cell's content you can use the [`heightForRowAt:`](https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614998-tableview) method of `UITableViewDelegate` – Paolo Oct 10 '17 at 15:59
  • I want to use the preferred UITableViewAutomaticDimension which I have configured. – Alexander MacLeod Oct 10 '17 at 16:01
0

Try this and see, it should work according to your need:

enter image description here

Set Top and Bottom constraints attribute Greater Than or Equal To and add horizontal center (Alight Center Y to superview) and show in this image.

Krunal
  • 77,632
  • 48
  • 245
  • 261
0

When UILabel is set to auto-adjust font size to fit, it does NOT auto-adjust the height of itself.

You have a couple options:

  1. set Baseline to Align Centers, and just accept that you will have top and bottom padding

  2. use code to calculate the "scaled font size" and update the font size of the label

DonMag
  • 69,424
  • 5
  • 50
  • 86