Search code examples
iosuilabel

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

  • 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)];
    }