runtime学习笔记

在项目开发中经常有许多封装过的.a文件,使用时经常会发现它们外部(.h) 并没有我们想要的东西。
我们并不能通过打点调用来解决。
所以我们有两个解决方案:1.通过继承并扩展。2.使用runtime。

下面我们举个简单的例子
1.UITextField
首先,我们遍历出UITextField的属性
使用runtime 需要导入头文件 #import

UITextField*textfield=[[UITextField alloc]init];

textfield.placeholder=@"123123";

textfield.frame=CGRectMake(0, 50, 320, 111);

[self.view addSubview:_textfield];

unsigned int outCount; // 1定义一个变量

Ivar *ivars = class_copyIvarList([textfield class], &outCount); // 2返回类的所有属性和变量(包括在@interface大括号中声明的变量)

for (int i = 0; i < outCount; i++) { // 3

Ivar ivar = ivars[i]; // 4

const char *ivarName = ivar_getName(ivar); // 5

const char *ivarType = ivar_getTypeEncoding(ivar); // 6

NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];

id value = [textfield valueForKey:key];

NSLog(@"实例变量名为:%s  值:%@  字符串类型为:%s", ivarName, ivarType); // 7

} // 8

free(ivars); // 9

通过控制台我们可以看到这一行

实例变量名为:_placeholderLabel 字符串类型为:@"UITextFieldLabel"

// 查看 _placeholderLabel 的类型
id value = [textfield valueForKey:@"_placeholderLabel"]; // 10
NSLog(@"value class:%@, value superclass:%@", NSStringFromClass([value class]), NSStringFromClass([value superclass])); // 11

通过控制台我们可以看到 _placeholderLabel 是继承于UILabel的

由此我们可以得到UITextField的placeholder 然后我们就可以对这个Label 进行修改了。


[textfield setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

未完待续。。。

你可能感兴趣的:(runtime学习笔记)