在某些場景我們想讓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);