简体   繁体   English

带有 UIButtons 的 Swift Keypath

[英]Swift Keypath with UIButtons

I'm trying to get a keypath to the selected property of an IBOutlet within a class.我正在尝试获取类中 IBOutlet 所选属性的关键路径。 But get: Type 'UIButton?' has no member 'isSelected'但是得到:输入Type 'UIButton?' has no member 'isSelected' Type 'UIButton?' has no member 'isSelected'

directly accessing the UIButton.isSelected keypath works, but doesn't fulfill my usecase.直接访问 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

what am I missing?我错过了什么?

#keyPath is just syntactic sugar that creates a string value, While ensuring that the keyPath is valid for the object you specify; #keyPath只是创建字符串值的语法糖,同时确保keyPath对您指定的对象有效; It helps to prevent crashes when using KVO, since it validates, at compile time, that your keyPath is valid, rather than crashing at runtime if it isn't.它有助于在使用 KVO 时防止崩溃,因为它会在编译时验证您的keyPath是否有效,而不是在运行时崩溃(如果不是)。

Accordingly, you don't specify a keyPath on a particular instance, you specify it on the object type.因此,您没有在特定实例上指定keyPath ,而是在对象类型上指定它。 This is why your first line works and the second two don't.这就是为什么您的第一行有效而后两行无效的原因。

You specify the specific object instance on which you want to observe the keyPath when you call addObserver :您在调用addObserver时指定要在其上观察keyPath的特定对象实例:

demo.addObserver(someObserver, forKeyPath: #keyPath(UIButton.isSelected), options: [], context: nil)

You could also say你也可以说

demo.addObserver(someObserver, forKeyPath: "selected", options: [], context: nil)

with the same result结果相同

But if you accidentally typed "slected" instead of "selected" you wouldn't find out until your app crashed at runtime, while #keyPath(UIButton.isSlected) will give you a compiler error straight away.但是,如果您不小心输入了"slected"而不是"selected"您将不会发现,直到您的应用程序在运行时崩溃,而#keyPath(UIButton.isSlected)会立即给您一个编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM