我有下面的 UINib 扩展方法,我想知道我是否可以为未归档的 View 设置一个委托(delegate)
public class func decodeView<T:UIView>(nibName name:String,className classType:T.Type,delegate:AnyObject) -> T {
let nib = UINib(nibName: name)
let topLevelObjects = nib.instantiateWithOwner(nil, options: nil)
let view = topLevelObjects[0] as T
view.setTranslatesAutoresizingMaskIntoConstraints(false)
//check if view.delegate exists then view.delegate = delegate
return view
}
最佳答案
如果您询问 Swift 是否支持反射,TL;DR:您需要从 NSObject
继承。否则您获得的信息有限。
在this question, Does Swift support reflection?你会得到关于你所拥有的可能性的更详细的讨论。
清除此部分后,可以在 SO Answer 中找到有关如何获取属性列表的示例。
尽管一种快速而肮脏的方法可能只是尝试访问该属性(使用 KVC)并在失败时捕获异常。 Swift 不支持 Try/Catch/Finally 结构,但是这 nice hack允许您编写如下代码:
SwiftTryCatch.try({
// try something
}, catch: { (error) in
println("\(error.description)")
}, finally: {
// close resources
})
关于ios - 快速检查对象的属性是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469197/