Getting Mouse Coordinates in Swift

后端 未结 2 386
走了就别回头了
走了就别回头了 2020-12-03 05:38

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

相关标签:
2条回答
  • 2020-12-03 06:05

    You can get the current mouse location in this way:

    • Declare this in your view controller class:

      var mouseLocation: NSPoint? { self.view.window?.mouseLocationOutsideOfEventStream }
      
    • Then, you can get the current mouse location and convert in your desired view coordinates:

      if let currentMouseLocation = self.mouseLocation{
      
           let pointInTargetView = self.**targetView**.convert(currentMouseLocation, from: self.view)
      
      }
      
    0 讨论(0)
  • 2020-12-03 06:07

    You should take a look at NSEvent method mouseLocation

    edit/update: Xcode 11 • Swift 5.1

    If you would like to monitor events on any window when your app is active, you can add a LocalMonitorForEvents matching mouseMoved mask and if it is not active a GlobalMonitorForEvents. Note that you need set to your window property acceptsMouseMovedEvents to true

    import Cocoa
    
    class ViewController: NSViewController {
        lazy var window: NSWindow = self.view.window!
        var mouseLocation: NSPoint { NSEvent.mouseLocation }
        var location: NSPoint { 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
                print(String(format: "%.0f, %.0f", self.mouseLocation.x, self.mouseLocation.y))
            }
        }
        override func viewWillAppear() {
            super.viewWillAppear()
            window.acceptsMouseMovedEvents = true
        }
    }
    

    Sample project

    0 讨论(0)
提交回复
热议问题