2013-06-21 26 views
0

我只是嘗試在窗口中全局接收觸摸事件,而不僅僅是在視圖中。 在我的代碼中,您可以在下面看到,我將在魔術觸控板中獲得觸控的絕對位置。只要光標在視圖內(紅色的NSRect)它可以正常工作,但是我怎樣才能在這個視圖之外接觸到觸摸。 我在許多社區和蘋果devcenter搜索解決方案,但沒有發現任何東西。 我認爲問題是這樣的:NSSet *touches = [ev touchesMatchingPhase:NSTouchPhaseTouching inView:nil]; NSEvent中沒有一個方法可以獲得每一個接觸嗎?通過NSEvent接收全球TouchEvents

希望有人能幫助我。

這裏我實現:

@implementation MyView 

- (id)initWithFrame:(NSRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code here. 
     [self setAcceptsTouchEvents:YES]; 
     myColor = [NSColor colorWithDeviceRed:1.0 green:0 blue:0 alpha:0.5]; 
    } 
    return self; 
} 

- (void)drawRect:(NSRect)dirtyRect { 
    // Drawing code here. 
    NSRect bounds = [self bounds]; 

    [myColor set]; 
    [NSBezierPath fillRect:bounds]; 

} 

- (void)touchesBeganWithEvent:(NSEvent *)ev { 
    NSSet *touches = [ev touchesMatchingPhase:NSTouchPhaseTouching inView:nil]; 

    for (NSTouch *touch in touches) { 

     NSPoint fraction = touch.normalizedPosition; 
     NSSize whole = touch.deviceSize; 
     NSPoint wholeInches = {whole.width/72.0, whole.height/72.0}; 
     NSPoint pos = wholeInches; 
     pos.x *= fraction.x; 
     pos.y *= fraction.y; 
     NSLog(@"%s: Finger is touching %g inches right and %g inches up " 
       @"from lower left corner of trackpad.", __func__, pos.x, pos.y); 

    } 
} 

回答

0

調用touchesMatchingPhase:inView:nil最後一個參數(你正在做的方式)將得到所有接觸。問題是touchesBeganWithEvent:將不會觸發不在觸摸區域的控件。

您可以使視圖成爲第一個響應者,它將首先將所有事件發送給它。見becomeFirstResponderResponder object