有时候我们需要使用控件的一些私用属性来方便我们的开发, 例如改变UITextField的placeholder文字的颜色
先查找UITextField的所有属性,进入头文件只能查找到一些属性, 并不能查找到私有属性
1.查找UITextField的所有属性
Object-C写法
1.1先导入<objc/runtime.h>头文件
具体实现:
第一个参数 : 是你要查找的类
第二个参数 : 查找到这个类的属性个数(需要填入的是unsigned int属性的地址)
我们以UITextField类为例
unsigned int count = 0;
Ivar *ivar = class_copyIvarList([UITextField class], &count);
for (int i = 0; i < count; i++) {
const char *charStr = ivar_getName(ivar[i]);
NSString *str = [NSString stringWithCString:charStr encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
}
结果 :
2017-06-12 11:37:09.002 ceshi[801:66588] _disabledBackgroundView
2017-06-12 11:37:09.002 ceshi[801:66588] _systemBackgroundView
2017-06-12 11:37:09.002 ceshi[801:66588] _floatingContentView
2017-06-12 11:37:09.002 ceshi[801:66588] _contentBackdropView
2017-06-12 11:37:09.003 ceshi[801:66588] _fieldEditorBackgroundView
2017-06-12 11:37:09.003 ceshi[801:66588] _fieldEditorEffectView
2017-06-12 11:37:09.003 ceshi[801:66588] _displayLabel
2017-06-12 11:37:09.003 ceshi[801:66588] _placeholderLabel
.......
利用KVC把placeholder文字的颜色改为红色
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
这样就可以简单的实现改功能, 是不是很简单。
改变前:
![](https://img.haomeiwen.com/i3499027/34468d6e3d34f1c7.png)
改变后:
![](https://img.haomeiwen.com/i3499027/81452954729d4586.png)
Swift写法
不用导入头文件
var count: UInt32 = 0
let ivar = class_copyIvarList(UITextField.self, &count)
for i in 0..<count {
var strName: UnsafePointer<Int8> = ivar_getName(ivar![Int(i)])
let str = String.init(utf8String: strName)
print(str)
}
Demo地址: Runtime与KVC集合的Demo
网友评论