首页 技术 正文
技术 2022年11月18日
0 收藏 738 点赞 4,942 浏览 1461 个字

因为项目中很多地方都有对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== || string == nil) { string = @" - - "; } // invoke originalimplemention
[self performSelector:@selector(setTextOriginal:) withObject:string];}@end
用:
///重写UIlabel的text属性
UILabel *tLab = [[UILabel alloc]initWithFrame:CGRectMake(, CGRectGetMaxY(btn.frame), , )];
tLab.text = nil;
[self.view addSubview:tLab];
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,071
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,549
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,397
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,174
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,809
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,889