Swift 带有 UIButtons 的键路径

Swift Keypath with UIButtons

我正在尝试获取 class 中 IBOutlet 的选定 属性 的键路径。但是得到: Type 'UIButton?' has no member '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) 会立即给您一个编译器错误。