重写UIlabel的setText:方法,过滤或者拦截text设置

因为项目中很多地方都有对UIlabel的赋值,但是text.length == 0 或者为空时并没有去给默认值,导致很多界面空间是白板, 所以不想一个一个去改。希望能重写UIlabel 的setText: 方法,在一个地方修改一下就行了。

参考了:https://blog.csdn.net/jiang314/article/details/52200714

写一个ULabel的分类 因为会先走分类里面的方法。 但是这样做会导致任何UILabel处都会先走分类方法,所以要考虑清楚。

//
//  UILabel+HHH.m
//  ZheDieLabel
//
//  Created by LiuWei on 2018/5/9.
//  Copyright © 2018年 xxx. All rights reserved.
//

#import "UILabel+HHH.h"
#import <objc/runtime.h>

@implementation UILabel (HHH)


//重写initialize
+ (void)initialize
{
    // 获取到UILabel中setText对应的method
    Method setText =class_getInstanceMethod([UILabel class], @selector(setText:));
    Method setTextMySelf =class_getInstanceMethod([self class],@selector(setTextHooked:));
    
    // 将目标函数的原实现绑定到setTextOriginalImplemention方法上
    IMP setTextImp =method_getImplementation(setText);
    class_addMethod([UILabel class], @selector(setTextOriginal:), setTextImp,method_getTypeEncoding(setText));
    
    //然后用我们自己的函数的实现,替换目标函数对应的实现
    IMP setTextMySelfImp =method_getImplementation(setTextMySelf);
    class_replaceMethod([UILabel class], @selector(setText:), setTextMySelfImp,method_getTypeEncoding(setText));
    
}


- (void)setTextHooked:(NSString *)string
{
    
//    //在这里插入过滤算法
//    string = [stringstringByReplacingOccurrencesOfString:@"
//              " withString:@"\r\n"];

    // do something what ever youwant
    if (string.length==0 || string == nil) {
        
        string = @" - - ";
        
    }
   
  // invoke originalimplemention
  [self performSelector:@selector(setTextOriginal:) withObject:string];
    
}


@end
用:
///重写UIlabel的text属性 UILabel *tLab = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(btn.frame), 200, 40)]; tLab.text = nil; [self.view addSubview:tLab];

 

posted @ 2018-05-09 14:50  liuw_flexi  阅读(1848)  评论(0编辑  收藏  举报