Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Starfox

macrumors 6502
Original poster
Apr 7, 2011
256
9
I want to implement swipe-to-navigate (like in Safari) in an app of mine and I have no idea as to where to start - I don't even know what keywords to search for, what class is responsible for this behavior etc. Does anyone know where to start?
 
I want to implement swipe-to-navigate (like in Safari) in an app of mine and I have no idea as to where to start - I don't even know what keywords to search for, what class is responsible for this behavior etc. Does anyone know where to start?

Look at NSResponder (touch and gesture events), and probably NSEvent.
 
The key functions are documented in NSEvent. Apple has a link to sample code in there as well. The API was added in 10.7. I just added swipe functionality to a Mandelbrot generation program I have written. The key methods happen in my main view class. You'll have to play around a bit to see what kind of effect you want during the swipe event. The Apple sample code does an animation while the swipe is happening. A little too sophisticated for my tastes.

Code:
- (BOOL)wantsScrollEventsForSwipeTrackingOnAxis:(NSEventGestureAxis)axis 
{
    // Inform the underlying view that we want horizontal scroll gesture events
    return (axis == NSEventGestureAxisHorizontal) ? YES : NO;
}


// Use horizontal swipe events to mean 'back' and 'forward', like a browser back button
- (void)scrollWheel:(NSEvent *)event 
{
    [event trackSwipeEventWithOptions:0 dampenAmountThresholdMin:-1 max:1 usingHandler:^(CGFloat gestureAmount, NSEventPhase phase, BOOL isComplete, BOOL *stop) {
        //NSLog(@"Got swipe amount %f phase %lu complete %d", gestureAmount, phase, isComplete);
        //if (isComplete)
        if (phase ==  NSEventPhaseBegan)
        {
            if (gestureAmount > 0)
            {
                // Simulate a 'back' operation
                [mandel_controller backButton:self];
            }
            else
            {
                // Simulate a 'forward' operation
                [mandel_controller forwardButton:self];

            }
        }
        *stop = NO;
    }];

}

One cool thing about this API is that if the user swaps the direction of their global preferences between the different directions, it will be transparent to your program. The underlying API handles this.
 
wantsScrollEventsForSwipeTrackingOnAxis: never gets called for my NSScrollView derived class - what am I missing?
 
wantsScrollEventsForSwipeTrackingOnAxis: never gets called for my NSScrollView derived class - what am I missing?

That's hard to say without seeing your code.

But I'd expect the document view to get these events, not the scrollview.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.