2011-03-18 27 views
8

我有一個NSView包含多個子視圖。其中一個子視圖是透明的,並且位於頂層。點擊NSView

我需要點擊這個視圖到下面的子視圖(以便下面的視圖獲得第一個響應者狀態),但所有的鼠標事件卡在頂視圖(alpha是1,因爲我畫它的東西 - 所以它只能通過透明區域點擊)。

我真的希望這個工作,因爲通常它。怎麼了?

+0

視圖設置爲不透明嗎? – Macmade 2011-03-18 20:45:20

+0

'-isOpaque'的視圖是'NO' – 2011-03-18 20:50:26

回答

10

這是另一種方法。它不需要創建一個新的窗口對象,並且比上面的findNextSiblingBelowEventLocation:方法更簡單(可能效率更高)。

- (NSView *)hitTest:(NSPoint)aPoint 
{ 
    // pass-through events that don't hit one of the visible subviews 
    for (NSView *subView in [self subviews]) { 
     if (![subView isHidden] && [subView hitTest:aPoint]) 
      return subView; 
    } 

    return nil; 
} 
1

將你的透明視圖放在它自己的子窗口中。

+0

爲什麼要這樣做? – 2011-03-21 13:02:11

+1

因爲通過窗口的透明部分解決點擊是窗口管理器的內在。你在上面做的工作沒有必要。 – NSResponder 2011-03-23 07:22:58

+0

哦,我剛剛意識到實際上有一個'-addChildWindow:'方法可以實現窗口的同步!對不起,我想我必須手動進行同步。 – 2011-03-23 12:06:01

1

我用這段代碼繞過了這個問題。

- (NSView *)findNextSiblingBelowEventLocation:(NSEvent *)theEvent { 
    // Translate the event location to view coordinates 
    NSPoint location = [theEvent locationInWindow]; 
    NSPoint convertedLocation = [self convertPointFromBase:location]; 

    // Find next view below self 
    NSArray *siblings = [[self superview] subviews]; 
    NSView *viewBelow = nil; 
    for (NSView *view in siblings) { 
    if (view != self) { 
     NSView *hitView = [view hitTest:convertedLocation]; 
     if (hitView != nil) { 
     viewBelow = hitView; 
     } 
    } 
    } 
    return viewBelow; 
} 

- (void)mouseDown:(NSEvent *)theEvent { 
    NSView *viewBelow = [self findNextSiblingBelowEventLocation:theEvent]; 
    if (viewBelow) { 
    [[self window] makeFirstResponder:viewBelow]; 
    } 
    [super mouseDown:theEvent]; 
}