1.首先:创建一个UILabel
的Category
;
.h
文件中
#import <UIKit/UIKit.h>
@interface UILabel (XHZLableInsets)
@property (nonatomic, assign) UIEdgeInsets xhzContentInsets;
@end
一般情况下,category中是不能创建属性的,所以需要使用到runtime
.m
文件
#import "UILabel+XHZLableInsets.h"
#import <objc/runtime.h>
static void *kAssociatedXhzCntentInsets = &kAssociatedXhzCntentInsets;
/// 获取UIEdgeInsets在水平方向上的值
CG_INLINE CGFloat UIEdgeInsetsGetHorizontalValue(UIEdgeInsets insets) {
return insets.left + insets.right;
}
/// 获取UIEdgeInsets在垂直方向上的值
CG_INLINE CGFloat UIEdgeInsetsGetVerticalValue(UIEdgeInsets insets) {
return insets.top + insets.bottom;
}
CG_INLINE void ReplaceMethod(Class _class, SEL _originSelector, SEL _newSelector){
Method originMethod = class_getInstanceMethod(_class, _originSelector);
Method newMethod = class_getInstanceMethod(_class, _newSelector);
BOOL isAddedMethod = class_addMethod(_class, _originSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
if (isAddedMethod) {
class_replaceMethod(_class, _newSelector, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
}else{
method_exchangeImplementations(originMethod, newMethod);
}
}
@implementation UILabel (XHZLableInsets)
//重写load方法
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ReplaceMethod([self class], @selector(drawTextInRect:), @selector(xhzDrawTextInRect:));
ReplaceMethod([self class], @selector(sizeThatFits:), @selector(xhzSzieThatFits:));
});
}
//替换原有的drawTextInRect方法
- (void)xhzDrawTextInRect:(CGRect)rect{
UIEdgeInsets insets = self.xhzContentInsets;
[self xhzDrawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
//替换原有的sizeThatFits方法
- (CGSize)xhzSzieThatFits:(CGSize)size{
if (CGSizeEqualToSize(size, CGSizeZero)) {
// NSAssert(NO, @"label size can not be CGSizeZero");
}
UIEdgeInsets insets = self.xhzContentInsets;
size = [self xhzSzieThatFits:CGSizeMake(size.width - UIEdgeInsetsGetHorizontalValue(insets), size.height - UIEdgeInsetsGetVerticalValue(insets))];
size.width += UIEdgeInsetsGetHorizontalValue(insets);
size.height += UIEdgeInsetsGetVerticalValue(insets);
return size;
}
//set方法
- (void)setXhzContentInsets:(UIEdgeInsets)xhzContentInsets{
objc_setAssociatedObject(self, &kAssociatedXhzCntentInsets, [NSValue valueWithUIEdgeInsets:xhzContentInsets], OBJC_ASSOCIATION_RETAIN);
}
//get方法
- (UIEdgeInsets)xhzContentInsets{
return [objc_getAssociatedObject(self, &kAssociatedXhzCntentInsets) UIEdgeInsetsValue];
}
@end
调用(在调用的地方需要引用类目的头文件)
self.introlLabel.xhzContentInsets = UIEdgeInsetsMake(10, 10, 10, 10);
使用前:
使用后