因為項目中很多地方都有對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];
