Łukasz
Łukasz

Reputation: 805

Why NotificationCenter doesn't pass NSPoint properly?

I'm trying to pass NSPoint via NotificationCenter. I have build a NSView subclass with defined three methods:

    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 )
    }

I registered observer as:

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

...and function to receive:

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

Notification works — when I press mouse button AppDelegate knows about it and fires mouseMovedTo but it receives only 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)
.....

How to pass NSPoint proper values? Is it bug?

I tried to pass NSEvent, but I had an errors when I tried to convert(event.locationInWindow, from: someView) inside AppDelegate. Some ideas?

Upvotes: 0

Views: 83

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100549

You need

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

Upvotes: 4

Related Questions