获取课程的所有密钥

时间:2015-06-17 15:11:23

标签: ios swift key-value-coding

最近,我使用func setValue(_ value: AnyObject?, forKey key: String)协议的NSKeyValueCoding函数以下列方式更改UIPickerDate的文字颜色:

class ColoredDatePicker: UIDatePicker {

    var changed = false

    override func addSubview(view: UIView) {
       if !changed {
          changed = true
          self.setValue(UIColor(red: 0.42, green: 0.42, blue: 0.42, alpha: 1), forKey: "textColor")

       }
       super.addSubview(view)
    }
}

关于question中的答案。它运作得很好。

但我的答案是:

我如何知道该类提供的名称,如上面使用的textColor

我试图找到任何可以获取所有名称或文档的内容,但到目前为止,我还没有找到任何可以获得由类等提供的的内容上述情况。

2 个答案:

答案 0 :(得分:4)

objective-c运行时为属性提供了这种类型的反射:

id UIDatePickerClass = objc_getClass("UIDatePicker");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(UIDatePickerClass, &outCount);
for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}

参考文档:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/c/func/class_copyPropertyList

编辑 - swift也有基本的反思:https://stackoverflow.com/a/24069875/1385467

答案 1 :(得分:3)

对于那些我们想要像@Adam这样的Swift解决方案的人,这里是:

var propertiesCount : CUnsignedInt = 0
let propertiesInAClass  = class_copyPropertyList(UIDatePicker.self, &propertiesCount)
var propertiesDictionary : NSMutableDictionary = NSMutableDictionary()

for var i = 0; i < Int(propertiesCount); i++ {
    var property = propertiesInAClass[i]
    var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding)
    println(propName)
}

Swift 4.1:

var propertiesCount: CUnsignedInt = 0
let propertiesInAClass = class_copyPropertyList(UIDatePicker.self, &propertiesCount)!
var propertiesDictionary: NSMutableDictionary = [:]

for i in 0..<propertiesCount {
    var property = propertiesInAClass[Int(i)]
    let propName = NSString(cString: property_getName(property), encoding: String.Encoding.utf8.rawValue)
    print(propName)
}