2

I have an UILabel, created in Universal storyboard, and I have mentioned all required constraints for its position OTHER THAN WIDTH. So it resizes itself as per the text set. Fantastic! Exactly what I want.

Problem starts here : It has background color as green color, but that color is wrapping my text tightly. I thus believe that making it a little wider can help me. But to do that, I need to know which method of my UILabel subclass is invoked. So that I can override and add additional width of 10 points.

BottomLine: Which UILabel method is invoked for resizing the label automatically after I assign it the text?

The way it currently looks :

enter image description here

Mayur Deshmukh
  • 1,169
  • 10
  • 25

2 Answers2

4

Unfortunately, we don't have any contentEdgeInsets property we can set on a UILabel (as we do have on a UIButton). If you want auto layout to continue to make the height and width constraints itself, you could make a subclass of UILabel and override the intrinsicContentSize and sizeThatFits to achieve what you want.

So, something like:

- (CGSize) intrinsicContentSize
{
    return [self addHorizontalPadding:[super intrinsicContentSize]];
}

- (CGSize)sizeThatFits:(CGSize)size
{
    return [self addHorizontalPadding:[super intrinsicContentSize]];
}

- (CGSize)addHorizontalPadding:(CGSize)size
{
    return CGSizeMake(size.width + (2*kSomeHorizontalPaddingValue), size.height);
}

Note that this only touches the horizontal padding, but can obviously be modified to add vertical padding as well.

Steffen D. Sommer
  • 2,896
  • 2
  • 24
  • 47
1

Steffen's answer is the way to go if you want to do that programmatically. I usually have a generic custom label subclass in my projects that adds a (IBInspectable) contentInsets property, amongst other things.

Anyways, just wanted to point out that you can also do this completely in IB by just wrapping your label in another view, give the container view the background color and add constraints for your horizontal padding.

Daniel Rinser
  • 8,855
  • 4
  • 41
  • 39