Mac可可 - 我如何检测触控板滚动手势?

Eri*_*pir 12 macos cocoa trackpad objective-c

我想检测滚动手势(两个手指在触控板上).我该怎么做?

spu*_*fle 25

看起来您想要覆盖视图的scrollWheel:方法.您可以使用NSEvent's deltaXdeltaY方法来获取用户滚动的数量.

码:

@implementation MyView

- (void)scrollWheel:(NSEvent *)theEvent {
    NSLog(@"user scrolled %f horizontally and %f vertically", [theEvent deltaX], [theEvent deltaY]);
}

@end
Run Code Online (Sandbox Code Playgroud)

您还可以查看" 处理触控板事件指南".这将向您展示如何捕获自定义手势,以及标准手势.

  • 请注意,Apple的文档建议使用`scrollingDeltaX`和`scrollingDeltaY`来访问NSScrollWheel值(OX 10.7及更高版本). (2认同)

小智 12

您应该通过NSView在自定义子类中实现触摸事件方法来实现.这些方法是:

- (void)touchesBeganWithEvent:(NSEvent *)event;
- (void)touchesMovedWithEvent:(NSEvent *)event;
- (void)touchesEndedWithEvent:(NSEvent *)event;
- (void)touchesCancelledWithEvent:(NSEvent *)event;
Run Code Online (Sandbox Code Playgroud)

NSEvent作为参数出现的对象包含有关涉及的触摸的信息.特别是,您可以使用以下方法检索它们:

-(NSSet *)touchesMatchingPhase:(NSTouchPhase)phase inView:(NSView *)view;
Run Code Online (Sandbox Code Playgroud)

此外,在自定义视图子类中,您必须首先将其设置为:

[self setAcceptsTouchEvents:YES]; 
Run Code Online (Sandbox Code Playgroud)

为了收到这样的事件.


APr*_*mer 6

要检测scrollWheel事件,请使用 - (void)scrollWheel:(NSEvent*)theEvent方法.

    - (void)scrollWheel:(NSEvent *)theEvent
    {
        //implement what you want
    }
Run Code Online (Sandbox Code Playgroud)

使用鼠标滚轮或触控板上的双指手势滚动时,将调用上述方法.

如果您的问题是确定是否通过鼠标或触控板生成scrollWheel事件,那么根据Apple的文档,这是不可能的.虽然这是一个解决方案,

- (void)scrollWheel:(NSEvent *)theEvent
    {
        if([theEvent phase])
        {
            // theEvent is generated by trackpad
        }
        else
        {
            // theEvent is generated by mouse
        }
    }
Run Code Online (Sandbox Code Playgroud)

你也可以使用-(void)beginGestureWithEvent:(NSEvent *)event;-(void)endGestureWithEvent:(NSEvent *)event.这些方法分别在之前和之后调用-(void)scrollWheel:(NSEvent *)theEvent.

有一种情况这不起作用 - 如果你更快地使用两个手指手势并且你的手指快速地离开触控板,那么你可能会遇到问题 - (内存没有被释放)

  • 我在 OSX 10.10 和 beginGestureWithEvent: 和 endGestureWithEvent: _not_ 滚动时调用了你的答案。根据文档,这两种方法仅针对触摸事件和手势激活。 (2认同)