UILable自定义内边距属性(UIEdgeInsets contentInset)
UILabel没有类似于UITextView中的contentInset属性可以自定义设置显示内容的内边距
可以通过给UILabel添加类目扩展自定义一个contentInset属性实现设置UILabel的内边距
给UILable添加扩展类目(UILabel+Insets)
UILabel+Insets.h 文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UILabel (Insets)
/**
和UITextView相似,内边距属性
控制字体与控件边界的间隙
*/
@property (nonatomic, assign) UIEdgeInsets contentInsets;
@end
NS_ASSUME_NONNULL_END
UILabel+Insets.m 文件
#import "UILabel+Insets.h"
@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)__drawTextInRect:(CGRect)rect{
id show = objc_getAssociatedObject(self, &kShowContentInsetsKey);
if (show) {
rect = UIEdgeInsetsInsetRect(rect, self.contentInsets);
}
[self __drawTextInRect:rect];
}
@end
使用效果杠杠滴
label.contentInsets = UIEdgeInsetsMake(10.f, 10.f, 10.f, 10.f)
效果对比
效果对比感觉好用请给个赞👍谢谢!
网友评论