Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac cocoa - how can i detect trackpad scroll gestures?

I want to detect scroll gestures (two fingers on trackpad). How should i do that?

like image 276
Erik Sapir Avatar asked Jul 10 '11 15:07

Erik Sapir


2 Answers

To detect the scrollWheel event, use - (void)scrollWheel:(NSEvent *)theEvent method.

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

The above method will be called when you scroll using the scroll wheel from your mouse or the two finger gesture from the trackpad.

If your question is to determine if the scrollWheel event is generated by mouse or trackpad, then according to Apple's documentation, this is not possible. Although here is a work around,

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

You might also use -(void)beginGestureWithEvent:(NSEvent *)event; and -(void)endGestureWithEvent:(NSEvent *)event. These methods are called before and after the -(void)scrollWheel:(NSEvent *)theEvent respectively.

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)

like image 84
AProgrammer Avatar answered Nov 15 '22 23:11

AProgrammer


Looks like you want to override your view's scrollWheel: method. You can use the NSEvent's deltaX and deltaY methods to get how much the user has scrolled by.

Code:

@implementation MyView

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

@end

You also may want to take a look at the Handling Trackpad Events Guide. This will show you how to capture custom gestures, in addition to standard ones.

like image 44
spudwaffle Avatar answered Nov 15 '22 22:11

spudwaffle