2012-04-08 40 views
1

我有一個NSEvent並要檢測點擊一個矩形的時候,所以這是我的代碼:鼠標事件的NSRect

- (void)mouseDown:(NSEvent *)event; 
{ 
    NSPoint clickedPoint = [event locationInWindow]; 
    //perform code for clickedPoint  
} 

而不是使用locationInWindow的我怎麼能轉換成一個矩形或視圖到NSPoint這樣它會檢查我是否點擊了矩形?謝謝!

回答

3

首先,考慮您是否真的要覆蓋mouseDown:或覆蓋mouseUp:可能是更好的選擇。如果此點擊類似於點擊某個按鈕之類的內容,則覆蓋mouseUp:而不是mouseDown:通常是更好的主意,因爲mouseUp:將允許用戶通過將鼠標拖出按鈕的矩形之前「放棄其主意」老鼠。

NSEventlocationInWindow在基窗口的座標中給出事件的位置。該位置轉換爲視圖本地座標系統,你可以使用NSViewconvertPoint:fromView:如以下:

- (void)mouseDown:(NSEvent *)event { 
    NSPoint eventLocation = [event locationInWindow]; 
    NSPoint location = [self convertPoint:eventLocation fromView:nil]; 
    // handle the logic of what to do given the point 
} 

更多信息請參見Cocoa Event-Handling Guide: Getting the Location of an Event