0

I got a UIView whose child is a UILabel. I then aligned the left, top, right, and bottom of the UILabel to that of its superview (the UIView) using constraints.

But what I'm getting is a UILabel that matches the height of its superview but not its intrinsic height (smaller or larger than its text content depending on the size of the UIView). What I expect is for the UIView to resize itself to fit exactly the height of the UILabel.

So how do I do this using only the interface builder?

Sid Go
  • 2,041
  • 3
  • 16
  • 29

4 Answers4

1

In order to make the UILabel keep its size and force the outer view to resize you can update the values for Content Hugging Priority to 1000 (a.k.a. Required). This can be done in the measurements panel when selecting the label in Interface Builder.

I think they are set as a default to 750.

This should (if there is nothing else causing the change) make the label take its intrinsic content size and force its superview to conform to that size also.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
0

Align top, trailing, bottom and leading of UILabel with UIView (add constraints). Remove height and bottom constraints from UIView if any.

If the content is large, you probably need to wrap UILabel into a UIScrollView in place of UIView. and add a bottom constraint to UIScrollView

Content Hugging Priority of UILabel (251) is more than that of UIView (250) by default. Verify this

Satish
  • 2,015
  • 1
  • 14
  • 22
0

It's super easy using auto-layout. Just, follow these steps

1 - Drag a UIView and align it vertically and horizontallyin centre.

2 - Now drag UILabel into the UIView and align the label also horizontally and vertically in centre.Now, the IB aligns the label at the centre WRT to the superview and not the UIView.So, change that in the size-inspector section.

3 - Once you have done that and all red lines are removed, select both the label and the UIView together using the command key.

4 - Now, give them constraints as follows

leading = 0, trailing = 0 and select the equal width and equal height.

There you are done.If you wanna test that the UIView size is respective to the label's content, try increasing the label's font to a bigger size and you will see that the size of the view will be the same as the size of the label.

There , you are done :-D. Hope, this was helpful.

Zahurafzal Mirza
  • 290
  • 1
  • 15
0

If someone is experiencing this issue, while:

  • Having 2 labels inside the UIView
  • Doing everything what was suggested here

In my case, I set Vertical Content Hugging Priority of BOTH UILabels to 1000. Then one of the labels had a different font. (ie. one label was supposed to be smaller than the other one)

The height was being ambiguous, because both labels were trying to force their height on the superview. Once I lowered the priority on the smaller label, everything worked fine.

Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76