当我使用KVO时,可以使用函数observeValueForKeyPath(.)的更改参数。才能知道价值。但是,当有多个按钮添加了观察者,我如何才能知道哪个按钮被更改?
例如,如下:
check1.addObserver(self, forKeyPath: "cell.state",
options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old,
context: nil)
check2.addObserver(self, forKeyPath: "cell.state",
options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old,
context: nil)
override func observeValueForKeyPath(keyPath: String, ofObject: AnyObject,
change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void> {
if keyPath == "cell.state" {
// I can get the value as follow, but how to know thevalue which button of?
if change[NSKeyValueChangeNewKey]?.boolValue == true {
self.isChecked = true
} else {
self.IsChecked = false
}
}发布于 2014-11-06 13:38:42
ofObject:参数是属性已被更改的对象。在Swift中,可以使用可选强制转换(as?)来验证对象是否具有适当的类型,然后将其与按钮进行比较:
if let button = ofObject as? NSButton {
if button == check1 {
// Checkbox 1 ...
}
}https://stackoverflow.com/questions/26779575
复制相似问题