在Swift中获取鼠标坐标

时间:2015-08-11 00:40:39

标签: macos swift

斯威夫特新手在这里。

我在完成一项应该是微不足道的任务时遇到了麻烦。我想做的就是获取鼠标光标的x,y坐标按需。我希望等待鼠标移动事件发生之前我才能抓住指针的坐标。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:20)

您应该查看NSEvent方法mouseLocation

编辑/更新: Xcode 8.2.1•Swift 3.0.2

如果您希望在应用处于活动状态时监控任何窗口上的事件,您可以添加与mouseMoved掩码匹配的LocalMonitorForEvents,如果它不是活动的,则为GlobalMonitorForEvents:

class ViewController: NSViewController {
    lazy var window: NSWindow = self.view.window!
    var mouseLocation: NSPoint {
        return NSEvent.mouseLocation
    }
    var location: NSPoint {
        return window.mouseLocationOutsideOfEventStream
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved]) {
            print("mouseLocation:", String(format: "%.1f, %.1f", self.mouseLocation.x, self.mouseLocation.y))
            print("windowLocation:", String(format: "%.1f, %.1f", self.location.x, self.location.y))
            return $0
        }
        NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved]) { _ in
            self.mouseLocation = NSEvent.mouseLocation()
            print(String(format: "%.0f, %.0f", self.mouseLocation.x, self.mouseLocation.y))
        }
    }
}

Swift 2

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

如果您想监控鼠标位置,您需要创建一个自定义窗口并覆盖mouseMoved事件,如下所示:

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

注意:您需要将您的窗口属性acceptMouseMovedEvents设置为true。

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

答案 1 :(得分:1)

您可以通过以下方式获取当前的鼠标位置:

  • 在您的视图控制器类中声明:

    var mouseLocation: NSPoint? { self.view.window?.mouseLocationOutsideOfEventStream }
    
  • 然后,您可以获得当前的鼠标位置并转换为所需的视图坐标:

    if let currentMouseLocation = self.mouseLocation{
    
         let pointInTargetView = self.**targetView**.convert(currentMouseLocation, from: self.view)
    
    }