在ios中,我们经常会有一些自定义的需求.但是有些需要修改的属性系统并没有抛出方法给我们修改.
作为一个对ios开发有点儿基础的人,都知道看到readOnly的属性可以通过setValueForKey来进行修改.
但是如果这个属性在.h里面搜索不到.是一种以私有属性的方式存在的属性怎么办.
我们可以利用runtime机制来获取私有属性.
首先.我们需要:
#import <objc/runtime.h>
导入一下runtime的头文件.
比如我想要修改UIDataPicker的文字颜色.
我们可以先便利一下UIDataPicker的属性:
unsigned int outCount =0;
Ivar *ivars =class_copyIvarList([UIDatePickerclass], &outCount);
for (NSInteger i =0; i < outCount; ++i) {
// 遍历取出该类成员变量
Ivar ivar = *(ivars + i);
NSLog(@"\n name = %s \n type = %s", ivar_getName(ivar),ivar_getTypeEncoding(ivar));
}
// 根据内存管理原则释放指针
free(ivars);
然后我们发现.UIDataPicker里面有个UIPickerView的属性.
然后我们去便利UIPickerView的属性:
unsigned int outCount =0;
Ivar *ivars =class_copyIvarList([UIPickerViewclass], &outCount);
for (NSInteger i =0; i < outCount; ++i) {
// 遍历取出该类成员变量
Ivar ivar = *(ivars + i);
NSLog(@"\n name = %s \n type = %s", ivar_getName(ivar),ivar_getTypeEncoding(ivar));
}
// 根据内存管理原则释放指针
free(ivars);
发现UIPickerView里面有一个textColor的属性.
因为这个属性是UIPickerView的属性.所以不能直接使用:
[self.dataPickerViewsetValue:[UIColorredColor] forKey:@"textColor"];
或者是:
[self.dataPickerViewsetValue:[UIColorredColor] forKey:@"pickerView.textColor"];
来修改颜色
而是应该使用keyPath来修改文字的颜色:
[self.dataPickerViewsetValue:[UIColorredColor] forKeyPath:@"pickerView.textColor"];
至此.我们已经修改完毕了.不知道大家学会了没有