【开发工具】UILabel 设置间距

优点:能够适应自动布局和 sizeToFit 适应大小
网上上的大多数方法,都没有重新 - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines ,实际上是有问题的

原博客地址:http://www.jianshu.com/p/5d9c48b42e58

效果:

_label.edgeInsets = UIEdgeInsetsMake(10, 20, 30, 40);

【开发工具】UILabel 设置间距_第1张图片
Paste_Image.png

_label.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);

【开发工具】UILabel 设置间距_第2张图片
Paste_Image.png

实现

#import 

@interface CustomizedPaddingLabel : UILabel

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end

#import "CustomizedPaddingLabel.h"

@implementation CustomizedPaddingLabel
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(20, 10, 20, 10);
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(20, 10, 20, 10);
    }
    return self;
}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    UIEdgeInsets insets = self.edgeInsets;
    CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)
                    limitedToNumberOfLines:numberOfLines];
    
    rect.origin.x    -= insets.left;
    rect.origin.y    -= insets.top;
    rect.size.width  += (insets.left + insets.right);
    rect.size.height += (insets.top + insets.bottom);
    
    return rect;
}

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}

@end

你可能感兴趣的:(【开发工具】UILabel 设置间距)