Getting Mouse Coordinates in Swift

后端 未结 2 399
走了就别回头了
走了就别回头了 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)
      
      }
      

提交回复
热议问题