gpt4 book ai didi

swift - NSView 无法观察 NSWindow 变化 - KVO 和 Swift

转载 作者:行者123 更新时间:2023-11-30 12:49:40 24 4
gpt4 key购买 nike

我很难让我的 NSView 观察其父 NSWindow 的变化。我在一个测试项目中尝试了这个,只不过是一个 NSWindow ,其中包含 NSViewMyView 子类,只是为了看看我是否遗漏了一些东西.

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 对象。我错过了什么?

最佳答案

所以看起来 NSWindowDidBecomeKey 是一个 Notification 需要发布到默认的 NotificationCenter 而不是窗口本身。这是正确的代码

class MyView: NSView {

//add observer on awake from nib
//works fine
override func awakeFromNib() {
if let win = self.window {
NotificationCenter.default.addObserver(self, selector: #selector(self.windowIsKey(_:)), name: .NSWindowDidBecomeKey, object: win)
}
}

//remove observer on dealloc
//allso works fine
deinit {
if let win = self.window {
NotificationCenter.default.removeObserver(self, name: .NSWindowDidBecomeKey, object: win)
}
}

//now this method is called and works fine
func windowIsKey(_ notification: Notification) {
Swift.print("worked!")
}
}

关于swift - NSView 无法观察 NSWindow 变化 - KVO 和 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41156907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com