我正在尝试获取类中 IBOutlet 的选定属性的键路径。但是得到:
键入“UIButton?”没有成员“isSelected”
直接访问 UIButton.isSelected 键路径可行,但不满足我的用例。
@objc class Demo: UIViewController{
@IBOutlet @objc dynamic weak var button: UIButton!
}
var demo = Demo()
print(#keyPath(UIButton.isSelected)) // no error
print(#keyPath(Demo.button.isSelected)) // error
print(#keyPath(demo.button.isSelected)) // error
我错过了什么?
最佳答案
#keyPath
只是创建字符串值的语法糖,同时确保 keyPath
对您指定的对象有效;它有助于防止在使用 KVO 时发生崩溃,因为它会在编译时验证您的 keyPath
是否有效,如果无效则不会在运行时崩溃。
因此,您无需在特定实例上指定 keyPath
,而是在对象类型上指定它。这就是为什么您的第一行有效而后两行无效的原因。
调用 addObserver
时,指定要在其上观察 keyPath
的特定对象实例:
demo.addObserver(someObserver, forKeyPath: #keyPath(UIButton.isSelected), options: [], context: nil)
你也可以说
demo.addObserver(someObserver, forKeyPath: "selected", options: [], context: nil)
同样的结果
但是,如果您不小心输入了 "slected"
而不是 "selected"
,您将无法发现,直到您的应用程序在运行时崩溃,而 #keyPath( UIButton.isSlected)
会立即给你一个编译器错误。
关于ios - 带有 UIButtons 的 Swift Keypath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56930175/