重寫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];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM