*运行时runtime苹果官方一套C语言库,进行底层操作的。
使用:
1>导入框架 #import <objc/runtime.h> 或 #import <objc/Message.h>
2> 以改变 UITextField 的 placeholder 的颜色为例:
UITextField 没有提供修改placeholder颜色的属性给我们,但是我们可以通过runtime获取UITextField隐藏的成员变量:
// 拷贝出所有的成员变量列表
Ivar *ivars = class_copyIvarList([UITextField class], &count);
for (int i = 0; i<count;i++){
// 取出成员变量
Ivar ivar = ivars[i];
// 打印成员变量名字和对应的类型
NSLog(@"%s %s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
}
// 释放
free(ivars)
![](https://i-blog.csdnimg.cn/blog_migrate/2abc641aa1fd741901f50628d1de7e8a.webp?x-image-process=image/format,png)
改变 placeholder 的颜色
UITextField *tf =[[UITextField alloc]initWithFrame:CGRectMake(100, 100, 200 ,30)];
tf.backgroundColor = [UIColor grayColor];
tf.placeholder = @"运行时";
[self.view addSubview:tf];
[tf setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
结果:
![](https://i-blog.csdnimg.cn/blog_migrate/f31b8829c9dda200bf371b6f6ae90426.webp?x-image-process=image/format,png)