MattY MattY - 1 month ago 20
Swift Question

Getting Mouse Coordinates in Swift

Swift newbie here.

I've been having trouble with a task that should be trivial. All I want to do is get the x,y coordinates of the mouse cursor on-demand. I would prefer not to wait for a mouse movement event to fire before I can grab the pointer's coords.

Would appreciate any help!

Answer

You should take a look at NSEvent method mouseLocation

Try like this:

import Cocoa
@NSApplicationMain

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    var mouseLocation: NSPoint {
        return NSEvent.mouseLocation()
    }

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        println( "Mouse Location X,Y = \(mouseLocation)" )
        println( "Mouse Location X = \(mouseLocation.x)" )
        println( "Mouse Location Y = \(mouseLocation.y)" )
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
}

If you would like to monitor the mouse location you will need to create a custom window and override mouseMoved event as follow:

class CustomWindow: NSWindow {
    var mouseLocation: NSPoint {
        return NSEvent.mouseLocation()
    }
    override func mouseMoved(theEvent: NSEvent) {
        println( "Mouse Location X,Y = \(mouseLocation)" )
        println( "Mouse Location X = \(mouseLocation.x)" )
        println( "Mouse Location Y = \(mouseLocation.y)" )
    }
}

note: you need set to your window property acceptsMouseMovedEvents to true.

func applicationDidFinishLaunching(aNotification: NSNotification) {
    window.acceptsMouseMovedEvents = true
}
Comments