我很难让NSView观察其父NSWindow中的更改。我在一个仅包含NSWindow子类MyViewNSView的测试项目中尝试了此操作,只是为了查看是否缺少某些内容。

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/

10-11 15:37