Cristian
Cristian

Reputation: 7145

Back/Forward Swipe Gesture in WebViews

I've looked at another post here on Stack Overflow concerning the back gesture, but mine is a little different.

How can I implement the swipe gesture to go 'Back' and 'Forward', to have an effect on the WebView the cursor is over? For example, if there are more than one, the gesture goes to and affects the appropriate view.

I suppose it would be the following code, but I do not know how to get the gesture methods to work:

- (void) backGesture {
    [(WebView *)self.theWebView goBack];
}

- (void) forwardGesture {
    [(WebView *)self.theWebView goForward];
}

Where 'theWebView' is the WebView the cursor is hovered over.

Is this even possible?

Upvotes: 1

Views: 3177

Answers (3)

bogdansrc
bogdansrc

Reputation: 1344

For two finger swipes, check out https://github.com/Kapeli/SwipableWebView

Upvotes: 0

mackworth
mackworth

Reputation: 5953

Well, you could add a category to webView with a swipeWithEvent methd, so that each view handles its own swipe (the three-finger variety; the two-finger scrolling is translated into mouse actions for the webview).

WebView+addSwipe.h:

#import <WebKit/WebKit.h>
@interface WebView (addSwipe)
@end

WebView+addSwipe.m:

#import "WebView+addSwipe.h"

@implementation WebView (addSwipe)

- (void)swipeWithEvent:(NSEvent *)event {
    CGFloat deltaX = [event deltaX];
    if (deltaX > 0) {
        NSLog(@"goForward %@ ", self);
        [self goForward];
    } else if (deltaX < 0) {
        NSLog(@"goBack%@ ", self);
        [self goBack];
    }
}

@end

And, if you WERE on iOS, attach two UISwipeGestureRecognizers to each view; one for each direction with separate actions:

-(void) backGesture:(UIGestureRecognizer *)sender {
    [sender.view goBack];
}

-(void) forwardGesture:(UIGestureRecognizer *) sender)
    [sender.view goForward];
}

with your viewController as the target. Each gesture action will be handed a sender, so sender.view will tell you which view had the swipe in it.

Note that "Three Finger Swipe to Navigate" must be on in Trackpad control panel on the system your program is running on.

Upvotes: 2

waylonion
waylonion

Reputation: 6976

You can create your own custom gestures, but you've got to implement touches began, touches moved and touches ended. The best way would be to have a CGPoint named startPoint and a second CGPoint named endPoint. On touches began, you store the location of the touch into startPoint. In touches ended, you store the end point in endPoint. To see if it was a back swipe, compare the x values of the two points! Here's a link on receiving touches: http://mobile.tutsplus.com/tutorials/iphone/ios-quick-tip-detecting-touches/
Hope this helped!

Upvotes: 0

Related Questions