UILabel text margin

I'm looking to set the left inset/margin of a UILabel and can't find a method to do so. The label has a background set so just changing its origin won't do the trick. It would be ideal to inset the text by 10px or so on the left hand side.


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

equivalent in Swift 3.1:

override func drawText(in rect: CGRect) {
    let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

As you might have gathered, this is an adaptation of tc.'s answer. It has two advantages over that one:

  • there's no need to trigger it by sending a sizeToFit message
  • it leaves the label frame alone - handy if your label has a background and you don't want that to shrink

  • 对于多行文本,可以使用NSAttributedString设置左右页边距。

    NSMutableParagraphStyle *style =  [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.alignment = NSTextAlignmentJustified;
    style.firstLineHeadIndent = 10.0f;
    style.headIndent = 10.0f;
    style.tailIndent = -10.0f;   
    
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:title attributes:@{ NSParagraphStyleAttributeName : style}];  
    
    UILabel * label = [[UILabel alloc] initWithFrame:someFrame];
    label.numberOfLines = 0;
    label.attributedText = attrText;
    

    The best approach to add padding to a UILabel is to subclass UILabel and add an edgeInsets property. You then set the desired insets and the label will be drawn accordingly.

    OSLabel.h

    #import <UIKit/UIKit.h>
    
    @interface OSLabel : UILabel
    
    @property (nonatomic, assign) UIEdgeInsets edgeInsets;
    
    @end
    

    OSLabel.m

    #import "OSLabel.h"
    
    @implementation OSLabel
    
    - (id)initWithFrame:(CGRect)frame{
        self = [super initWithFrame:frame];
        if (self) {
            self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        return self;
    }
    
    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
    }
    
    - (CGSize)intrinsicContentSize
    {
        CGSize size = [super intrinsicContentSize];
        size.width  += self.edgeInsets.left + self.edgeInsets.right;
        size.height += self.edgeInsets.top + self.edgeInsets.bottom;
        return size;
    }
    
    @end
    
    链接地址: http://www.djcxy.com/p/4836.html

    上一篇: 将UIButton上的文本和图像与imageEdgeInsets和titleEdgeInsets对齐

    下一篇: UILabel文本边距