修改UILabel的UIEdgeInsets

1.首先:创建一个UILabelCategory

创建类目

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

使用前:
这里写图片描述

使用后
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值