Dan Gonzalez
Dan Gonzalez

Reputation: 100

Swift - Get mouse click coordinates within a UIElement

I'm making a Cocoa app for OS X using Swift. The app is supposed to be very simple: basically it displays an image, then listens for mouse clicks within that image and returns the 2D mouse coords based on the origin of the image (not the absolute mouse coordinates). I'm not sure if I described that well, but for example once it registers a mouse click event, it should tell me that the mouse click occurred 23 pixels to the right and 57 pixels down from the 0,0 point of the image (or whatever the units would be).

So far I have this, but all I've been able to do is get it to return the absolute mouse coordinates:

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

}

How would I go about getting the information I need?

Upvotes: 0

Views: 1994

Answers (1)

donkey
donkey

Reputation: 4363

What about

sender.convertPoint(mouseLocation, fromView:nil)

Upvotes: 1

Related Questions