为什么NotificationCenter无法正确通过NSPoint?

时间:2018-09-21 11:56:46

标签: swift macos nsnotificationcenter

我正在尝试通过NotificationCenter传递NSPoint。我用定义的三种方法构建了一个NSView子类:

    override func mouseDragged(with event: NSEvent) {
        post(event: event)
    }

    override func mouseDown(with event: NSEvent) {
        post(event: event)
    }

    func post(event: NSEvent) {
        let point  = convert(event.locationInWindow, from: nil)
        print ("sending \(point)")
        NotificationCenter.default.post (
            name: NSNotification.Name.mousePositionChanged,
            object: point )
    }

我将观察员注册为:

NotificationCenter.default.addObserver(
                    self,
                    selector: #selector(self.mouseMovedTo(_:)),
                    name: NSNotification.Name.mousePositionChanged,
                    object: nil)

...并具有接收功能:

@objc func mouseMovedTo(_ point:NSPoint) {
    print ("receive \(point)")
}

通知有效-当我按下鼠标按钮AppDelegate知道并触发mouseMovedTo时,通知仅接收Point(0,0):

sending (0.350715866416309, 0.308759973404255)
receive (0.0, 0.0)
sending (0.350187768240343, 0.30802384118541)
receive (0.0, 0.0)
sending (0.349039364270386, 0.306409099544073)
receive (0.0, 0.0)
.....

如何传递NSPoint适当的值?是虫子吗?

我尝试传递NSEvent,但是在AppDelegate中尝试convert(event.locationInWindow, from: someView)时遇到错误。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您需要

@objc func mouseMovedTo(_ notification:NSNotification) {
  print ("receive \(notification.object)")
}