2011-01-09 20 views
9

我是Mac新手,我想在光標進入或退出主窗口時觸發事件。我讀了一些關於NSTrackingArea的內容,但我不明白該怎麼做。如何使用NSTrackingArea

回答

13

Apple爲NSTrackingAreas提供了文檔和示例。

跟蹤鼠標進入或存在窗口的最簡單方法是在窗口的contentView中設置跟蹤區域。然而,這將不跟蹤窗口的工具欄

就像一個簡單的例子,在自定義內容視圖代碼:

- (void) viewWillMoveToWindow:(NSWindow *)newWindow { 
    // Setup a new tracking area when the view is added to the window. 
    NSTrackingArea* trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options: (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways) owner:self userInfo:nil]; 
    [self addTrackingArea:trackingArea]; 
} 

- (void) mouseEntered:(NSEvent*)theEvent { 
    // Mouse entered tracking area. 
} 

- (void) mouseExited:(NSEvent*)theEvent { 
    // Mouse exited tracking area. 
} 

你也應該實現的NSView的updateTrackingAreas方法和測試活動的跟蹤區域,以確保這是正確的。

+1

好的,這將是一個noob問題,但我必須在哪裏放置代碼?我在哪裏可以找到自定義視圖的代碼?在使用插座和動作時,我是否必須將對象連接到Interface Builder中的視圖? – icant 2011-01-10 20:24:03

+3

此代碼應放置在自定義UIView子類中。然後應該添加自定義UIView作爲窗口的內容視圖。使用Interface Builder,爲窗口創建或選擇一個內容視圖,並使用Interface Builder檢查器面板指定它的類作爲您的自定義UIView的類。 – 2011-01-10 20:31:59

5

通過Matt Bierner真的幫助我;需要執行-viewWillMoveToWindow:方法。

我還想補充一點,你也將需要實現這一點,如果你要處理的跟蹤區域視圖時調整大小:

- (void)updateTrackingAreas 
{ 
    // remove out-of-date tracking areas and add recomputed ones.. 
} 
在自定義子類

,來處理視圖的變化的幾何形狀;這將自動爲你調用。