修改UILabel的UIEdgeInsets

来源:互联网 发布:java代码加密工具 编辑:程序博客网 时间:2024/06/04 18:17

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

使用前:
这里写图片描述

使用后
这里写图片描述

阅读全文
0 0
原创粉丝点击