我只是尝试在窗口中全局接收触摸事件,而不仅仅是在视图中。在我的代码中,您可以在下面看到,我将在魔术触控板上获得触摸的绝对位置。只要光标在视图内(红色的 NSRect),它就可以正常工作,但我如何才能在该视图之外接收触摸。我在许多社区和苹果开发中心搜索了解决方案,但一无所获。我认为问题是这样的:NSSet *touches = [ev touchesMatchingPhase:NSTouchPhaseTouching inView:nil];
NSEvent 中没有一种方法可以得到每一次触摸吗?
希望有人可以帮助我。
这是我的实现:
@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);
}
}