PDA

View Full Version : Swipe to navigate




Starfox
Jan 10, 2012, 05:16 AM
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?



gnasher729
Jan 10, 2012, 06:55 AM
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.

mfram
Jan 10, 2012, 12:34 PM
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.

- (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.

Starfox
Jan 11, 2012, 02:31 PM
wantsScrollEventsForSwipeTrackingOnAxis: never gets called for my NSScrollView derived class - what am I missing?

gnasher729
Jan 11, 2012, 04:06 PM
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.