Annachiara Annachiara - 4 years ago 113
iOS Question

Adding space/padding to a UILabel

I have a

where I want to add space in the top and in the bottom.
With minimun height in constrainst I've modified it to:

enter image description here

To do this I've used:

override func drawTextInRect(rect: CGRect) {
var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))


But I've to find a different method because if I write more than two lines the problem is the same:

enter image description here

Answer Source

If you want to stick with UILabel, without subclassing it, Mundi has given you a clear solution.

If alternatively you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets.

Using a UITextView you would only need to provide the insets (OBJ-C):

textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);

Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method

- (void)drawTextInRect:(CGRect)uiLabelRect {
    UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
    [super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];

You could additionally provide your new subclassed UILabel with a insets variable for TOP, LEFT, BOTTOM and RIGHT.

An example code could be:

In .h (OBJ-C)

float topInset, leftInset,bottomInset, rightInset;

In .m (OBJ-C)

- (void)drawTextInRect:(CGRect)uiLabelRect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];

EDIT #1:

From what I have seen, it seems you have to override the intrinsicContentSize of the UILabel when subclassing it.

So you should override intrinsicContentSize like:

- (CGSize) intrinsicContentSize {
    CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
    intrinsicSuperViewContentSize.height += topInset + bottomInset ;
    intrinsicSuperViewContentSize.width += leftInset + rightInset ;
    return intrinsicSuperViewContentSize ;

And add the following method to edit your insets, instead of editing them individually:

- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
    topInset =;
    leftInset = edgeInsets.left;
    rightInset = edgeInsets.right; 
    bottomInset = edgeInsets.bottom;
    [self invalidateIntrinsicContentSize] ;

It will update the size of your UILabel to match the edge insets and cover multiline necessity you referred.

Edit #2

After searching a bit I have found this Gist with a IPInsetLabel. If none of those solutions work you could try it out.

Edit #3

There was similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download