UILabel增加内边距属性

在某些场景我们想让Label像UIButton这种控件一样,可以设置内容边距,来使整体布局可拓展性增强。刚好项目中遇到需要使用的场景,就通过category为UILabel添加内边距属性。


Demo下载:https://github.com/icofans/UIlabel-Insets


.h

@interface UILabel (Insets)

/**

和UIbutton相似,内边距属性

控制字体与控件边界的间隙

*/

@property (nonatomic, assign) UIEdgeInsets contentInsets;

@end


.m

@implementation UILabel (Insets)

static char kContentInsetsKey;

static char kshowContentInsetsKey;

- (void)setContentInsets:(UIEdgeInsets)contentInsets

{

    objc_setAssociatedObject(self, &kContentInsetsKey, NSStringFromUIEdgeInsets(contentInsets), OBJC_ASSOCIATION_COPY_NONATOMIC);

    objc_setAssociatedObject(self, &kshowContentInsetsKey, @YES, OBJC_ASSOCIATION_COPY_NONATOMIC);


}

- (UIEdgeInsets)contentInsets

{

    return UIEdgeInsetsFromString(objc_getAssociatedObject(self, &kContentInsetsKey));

}

+ (void)load

{

    [super load];

    // class_getInstanceMethod()

    Method fromMethod = class_getInstanceMethod([self class], @selector(drawTextInRect:));

    Method toMethod = class_getInstanceMethod([self class], @selector(tt_drawTextInRect:));

    // class_addMethod()

    if (!class_addMethod([self class], @selector(drawTextInRect:), method_getImplementation(toMethod), method_getTypeEncoding(toMethod))) {

        method_exchangeImplementations(fromMethod, toMethod);

    }

}

- (void)tt_drawTextInRect:(CGRect)rect

{

    BOOL show = objc_getAssociatedObject(self, &kshowContentInsetsKey);

    if (show) {

        rect = UIEdgeInsetsInsetRect(rect, self.contentInsets);

    }

    [self tt_drawTextInRect:rect];

}

@end


使用很简单

textLabel.contentInsets = UIEdgeInsetsMake(0, 16, 0, 0);

你可能感兴趣的:(UILabel增加内边距属性)