Search code examples
iphoneios7uilabel

Add padding to programmatically created UILabel


How can I add padding to the UIlabel text that created programmatically?

NSArray *collectionViewArrayTitle = _titleArray[collectionView.index];
 NSString *title=   collectionViewArrayTitle[indexPath.item];
 newslabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 80, 130, 50)];
_newslabel.textColor=[UIColor whiteColor];
_newslabel.backgroundColor=[UIColor blackColor]  ;
_newslabel.alpha=1.0f;
_newslabel.text=title;
_newslabel.tag=collectionView.index;
_newslabel.lineBreakMode=NSLineBreakByTruncatingTail;
_newslabel.numberOfLines=4;

Solution

  • The best way to add 'padding' to your labels is to make a subclass of UILabel and add the edgeInsets property.

    CustomLabel.h
    
    #import <UIKit/UIKit.h>
    
    @interface CustomLabel : UILabel
    
    @property (nonatomic, assign) UIEdgeInsets edgeInsets;
    
    @end
    CustomLabel.m
    
    #import "CustomLabel.h"
    
    @implementation CustomLabel
    
    - (id)initWithFrame:(CGRect)frame{
        self = [super initWithFrame:frame];
        if (self) {
            self.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 0); //customize padding here
        }
        return self;
    }
    
    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
    }
    
    @end
    

    Another way of adding padding is to use a second layer. This may be a lot easier to accomplish but is imo not the most clean way to deal with it. You can add a UIView with the size of the label and then adjust that frame with some padding. Then you can add the intended UILabel to this view and play with the origins to get the right padding this way.