iOS 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);

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容