13

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

4

3 回答 3

27

看起来您想覆盖视图的scrollWheel:方法。您可以使用NSEvent'sdeltaXdeltaY方法来获取用户滚动了多少。

代码:

@implementation MyView

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

@end

您可能还想查看处理触控板事件指南。除了标准手势之外,这将向您展示如何捕获自定义手势。

于 2011-07-10T16:31:22.993 回答
13

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

- (void)touchesBeganWithEvent:(NSEvent *)event;
- (void)touchesMovedWithEvent:(NSEvent *)event;
- (void)touchesEndedWithEvent:(NSEvent *)event;
- (void)touchesCancelledWithEvent:(NSEvent *)event;

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

-(NSSet *)touchesMatchingPhase:(NSTouchPhase)phase inView:(NSView *)view;

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

[self setAcceptsTouchEvents:YES]; 

为了接收这样的事件。

于 2011-07-10T16:34:57.663 回答
7

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

    - (void)scrollWheel:(NSEvent *)theEvent
    {
        //implement what you want
    }

当您使用鼠标滚轮或触控板的两指手势滚动时,将调用上述方法。

如果您的问题是确定 scrollWheel 事件是由鼠标还是触控板生成的,那么根据 Apple 的文档,这是不可能的。虽然这是一个解决方法,

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

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

There is a case when this will not work - if you use the two finger gesture faster and take your fingers out of the trackpad pretty fast, then you might have issues here - (Memory is not getting released)

于 2012-12-11T15:42:35.257 回答