How can I add padding to the intrinsic content size of UILabel?
Asked Answered
H

4

21

I'm using autolayout on iOS7 and I have a problem like this:

I'm putting a UILabel onto a UIView and I'm arranging my autolayout constraints so that the label's centerX = parent view's centerX. I'm not giving any width constraint to the label. When I set the label's text on runtime, the label is drawn just wide enough for the text to fit, there are no margins/paddings on the left and right sides. What I want is to have some padding on the left and right sides, so that the text doesn't begin just where the label begins. The hack to achieve this could be setting the text as @" text " but of course that's not the way to go :)

How can I achieve what I want?

Hydr answered 1/1, 2014 at 23:5 Comment(0)
P
34

You can extend UILabel and override the intrinsicContentSize by yourself. Please make sure you have set the textAlignment = NSTextAlignmentCenter as well.

-(CGSize)intrinsicContentSize{
    CGSize contentSize = [super intrinsicContentSize];
    return CGSizeMake(contentSize.width + 50, contentSize.height);
}

Swift 5.0

open override var intrinsicContentSize: CGSize {
    let size = super.intrinsicContentSize
    return CGSize(width: size.width + 16, height: size.height)
}

This probably only works when you only have just one line of text to display.

Pratfall answered 2/1, 2014 at 2:10 Comment(0)
B
7

You can create a UILabel subclass and override intrinsicContent,

-(CGSize)intrinsicContentSize {
    CGSize s = [super intrinsicContentSize];
    s = CGSizeMake(s.width + 20, s.height);
    return s;
}

This will add a padding of 20 points to the width. If you want your text in the middle, be sure to set the text alignment to center.

Bookkeeping answered 2/1, 2014 at 1:39 Comment(0)
U
3

If you're using auto layout, you can set the horizontal constraints and use an NSDictionary in the metrics parameter to set this dynamically.

For instance, if you wanted to give a 10pt padding to the inner content of a UIButton, you could do something like the following:

NSDictionary *padding = @{ @"padding" : @(button.intrinsicContentSize.width + 20) };
NSArray *buttonHConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button(==padding)]|" options:0 metrics:padding views:NSDictionaryOfVariableBindings(button)];
Urushiol answered 15/4, 2015 at 17:57 Comment(0)
T
1

If you are trying to give the UILabel a different colour to its parent view, then you will need to enclose the UILabel in a UIView with the padding and the background colour you want. If your UILabels background colour is the same as its parent view, then I don't understand the problem just use auto layout to specify how much space you want relative to the thing it is next to.

Tilsit answered 2/1, 2014 at 1:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.