Swift - 在UIElement中获取鼠标单击坐标

时间:2016-05-16 22:59:23

标签: xcode swift macos

我正在使用Swift为OS X制作一个Cocoa应用程序。该应用程序应该非常简单:基本上它会显示一个图像,然后在该图像中侦听鼠标点击并根据图像的原点(而不是绝对鼠标坐标)返回2D鼠标坐标。我不确定我是否描述得那么好,但是例如一旦它注册鼠标点击事件,它应该告诉我鼠标点击发生在右边23个像素和从图像的0点0点向下57个像素(或者无论单位是什么。)

到目前为止,我有这个,但我能做的就是让它返回绝对鼠标坐标:

import Cocoa

class ViewController: NSViewController {

    @IBOutlet var ImageButton: NSButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        let fileName = "myTestImage.jpg"
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! + "/TrainingSet/" + fileName
        //"/Users/dan/Documents/myTestImage.jpg"
        let myImage = NSImage(contentsOfFile: path)
        ImageButton.image = myImage

    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func ImageButtonClicked(sender: NSButton) {

        //let x = sender
        //let coords = x.frame

        let mouseLocation = NSEvent.mouseLocation();
        print( "Mouse Location X,Y = \(mouseLocation)" )
        print( "Mouse Location X = \(mouseLocation.x)" )
        print( "Mouse Location Y = \(mouseLocation.y)" )
    }

}

我如何获取所需信息?

1 个答案:

答案 0 :(得分:1)

怎么样?
sender.convertPoint(mouseLocation, fromView:nil)