2016-05-16 159 views
0

我正在使用Swift爲OS X製作Cocoa應用程序。該應用程序應該非常簡單:基本上它會顯示圖像,然後偵聽該圖像中的鼠標點擊,並根據圖像的原點(而不是鼠標的絕對座標)返回2D鼠標座標。我不確定是否描述得很好,但是例如一旦註冊了鼠標點擊事件,它應該告訴我鼠標點擊發生在右邊23像素和圖像0,0點57像素之間(或任何單位將是)。Swift - 在UIElement中獲取鼠標點擊座標

到目前爲止,我有這個,但我已經能夠做的就是它返回的絕對鼠標座標:

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

你試過sender.superview.convertPoint(mouseLocation,toView:)? – xhamr

回答

1

什麼

sender.convertPoint(mouseLocation, fromView:nil)