0
我很難讓我的NSView
觀察其父母NSWindow
中的更改。我在一個測試項目上嘗試了這個測試項目,僅僅包含一個NSWindow
,其中包含MyView
的子類NSView
,只是爲了看看我是否缺少了一些東西。NSView無法觀察NSWindow變化 - KVO和Swift
class MyView: NSView {
//add observer on awake from nib
//works fine
override func awakeFromNib() {
if let win = self.window {
win.addObserver(self, forKeyPath: Notification.Name.NSWindowDidBecomeKey.rawValue, options: .new, context: nil)
}
}
//remove observer on dealloc
//allso works fine
deinit {
if let win = self.window {
win.removeObserver(self, forKeyPath: Notification.Name.NSWindowDidBecomeKey.rawValue)
}
}
//never gets called
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
Swift.print(keyPath ?? "")
Swift.print("worked!")
}
override func draw(_ dirtyRect: NSRect) {
NSColor.blue.set()
NSBezierPath.fill(dirtyRect)
}
}
我也嘗試了here的建議,但沒有運氣。我也檢查了其他答案並找不到答案。大多數封面製作您自己的類KVO兼容。我想觀察NSWindow對象。我錯過了什麼?