有時候我們需要使用控件的一些私用屬性來方便我們的開發(fā), 例如改變UITextField的placeholder文字的顏色
先查找UITextField的所有屬性,進(jìn)入頭文件只能查找到一些屬性, 并不能查找到私有屬性
1.查找UITextField的所有屬性
Object-C寫法
1.1先導(dǎo)入<objc/runtime.h>頭文件
具體實(shí)現(xiàn):
第一個參數(shù) : 是你要查找的類
第二個參數(shù) : 查找到這個類的屬性個數(shù)(需要填入的是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);
}
結(jié)果 :
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"];
這樣就可以簡單的實(shí)現(xiàn)改功能, 是不是很簡單。
改變前:
改變后:
Swift寫法
不用導(dǎo)入頭文件
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