Add left/right horizontal padding to UILabel

I need to create a UILabel with a background color, and I'd like to add some left/right leading/trailing horizontal padding.

But every solution I've found seems like a nasty hack.

What is the 'standard' way to achieve this from iOS 5 forward?

A screenshot to illustrate my scenario:

left padding needed


Solution 1:

For a full list of available solutions, see this answer: UILabel text margin


Try subclassing UILabel, like @Tommy Herbert suggests in the answer to [this question][1]. Copied and pasted for your convenience:

I solved this by subclassing UILabel and overriding drawTextInRect: like this:

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

Solution 2:

The most important part is that you must override both intrinsicContentSize() and drawTextInRect() in order to account for AutoLayout:

var contentInset: UIEdgeInsets = .zero {
    didSet {
        setNeedsDisplay()
    }
}

override public var intrinsicContentSize: CGSize {
    let size = super.intrinsicContentSize
    return CGSize(width: size.width + contentInset.left + contentInset.right, height: size.height + contentInset.top + contentInset.bottom)
}

override public func drawText(in rect: CGRect) {
    super.drawText(in: UIEdgeInsetsInsetRect(rect, contentInset))
}

Solution 3:

add a space character too the string. that's poor man's padding :)

OR

I would go with a custom background view but if you don't want that, the space is the only other easy options I see...

OR write a custom label. render the text via coretext

Solution 4:

#define PADDING 5

@interface MyLabel : UILabel

@end

@implementation MyLabel

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = UIEdgeInsetsMake(0, PADDING, 0, PADDING);
    CGRect rect = UIEdgeInsetsInsetRect(rect, insets);
    return [super drawTextInRect:rect];
}

- (CGRect)textRectForBounds:(CGRect)bounds
     limitedToNumberOfLines:(NSInteger)numberOfLines
{
    CGSize size = CGSizeMake(999, 999);
    CGRect rect = [self.attributedText
                   boundingRectWithSize:size
                                options:NSStringDrawingUsesLineFragmentOrigin
                                context:nil];
    return CGRectInset(rect, -PADDING, 0);
}

@end

Solution 5:

UIView* bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 70)];
bg.backgroundColor = [UIColor blackColor];
UILabel* yourLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, y, yourWidth, yourHeight)];
[bg addSubview:yourLabel];

[self addSubview:bg];