【发布时间】:2019-05-28 07:47:49
【问题描述】:
我对 Swift 和“Apple”编程很陌生,如果我的问题很愚蠢,请原谅。
我正在尝试对 NSPopupButton 进行子类化,以添加用于绑定菜单项的图像属性的选项。
我想重写“绑定”功能:
override func bind(_ binding: NSBindingName, to observable: Any, withKeyPath keyPath: String, options: [NSBindingOption : Any]? = nil)
为了观察“observable”参数,这是我写到现在的代码:
class WDPopupButton: NSPopUpButton
{
static let ImageBindingContext: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(mutating: "imageContext")
override func bind(_ binding: NSBindingName, to observable: Any, withKeyPath keyPath: String, options: [NSBindingOption : Any]? = nil)
{
if(binding == NSBindingName.image)
{
guard let observableObject = observable as AnyObject? else
{
return
}
observable.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)
...
}
}
}
但我收到以下错误:
Value of type 'Any' has no member 'addObserver'
我的问题是,我需要做什么才能在 observable 参数上调用 addObserver?
如您所见,我确实尝试将 observable 转换为 AnyObject 类型,但随后收到另一个错误,我找不到解决方案。
我将 addObserver 行更改为:
observableObject.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)
得到:
Type of expression is ambiguous without more context
如果将 observable 转换为 AnyObject 是解决方案,那么这个错误意味着什么,我做错了什么?
谢谢
【问题讨论】: