【问题标题】:Swift Keypath with UIButtons带有 UIButtons 的 Swift Keypath
【发布时间】:2019-07-08 07:27:44
【问题描述】:

我正在尝试获取类中 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

我错过了什么?

【问题讨论】:

  • 您不需要使用键路径来访问对象实例上的属性。只需print(demo.button.isSelected)
  • 这只是一个激进的简化示例。我正在尝试在 KVO 的上下文中使用它,但在示例中不需要这样做。
  • 好的。答案是一样的——你将 keypath 与对象一起使用,而不是与实例一起使用。您只需将属性与实例一起使用。您还可以将对象键路径与 addObserver 一起使用,指定要在其上观察键路径的实例

标签: ios swift keypaths swift-keypath


【解决方案1】:

#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) 会立即给您一个编译器错误。

【讨论】:

  • 谢谢,我终于明白为什么它是对象类型了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
  • 2011-11-21
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多