Swipe gesture for back/forward in UIWebView?

user4428017 picture user4428017 · Aug 14, 2015 · Viewed 11.6k times · Source

I have a WebView in my app.

Because it is a tabbed application I'm not able to add buttons for going back/forward on the website.

I want to go back/forward by swiping. Right swipe from the left side/edge is back… like in Safari browser for iOS.

How can I do it? I think i should use "Screen Edge Pan Gesture Recognizer", right?

Answer

Gabriel Madruga picture Gabriel Madruga · Mar 28, 2017

Accepted answer in Swift 3:

override func viewDidLoad() {
    super.viewDidLoad()

    let swipeLeftRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
    let swipeRightRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
    swipeLeftRecognizer.direction = .left
    swipeRightRecognizer.direction = .right

    webView.addGestureRecognizer(swipeLeftRecognizer)
    webView.addGestureRecognizer(swipeRightRecognizer)
}

@objc private func handleSwipe(recognizer: UISwipeGestureRecognizer) {
    if (recognizer.direction == .left) {
        if webView.canGoForward {
            webView.goForward()
        }
    }

    if (recognizer.direction == .right) {
        if webView.canGoBack {
            webView.goBack()
        }
    }
}