Swift

WebView にスワイプで戻る、進む機能をつける

More than 3 years have passed since last update.


ViewController.swift

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
...
self.setupSwipeGestures()
}

func setupSwipeGestures() {
// 右方向へのスワイプ
let gestureToRight = UISwipeGestureRecognizer(target: self.webView, action: "goBack")
gestureToRight.direction = UISwipeGestureRecognizerDirection.Right
self.webView.addGestureRecognizer(gestureToRight)

// 左方向へのスワイプ
let gestureToLeft = UISwipeGestureRecognizer(target: self.webView, action: "goForward")
gestureToLeft.direction = UISwipeGestureRecognizerDirection.Left
self.webView.addGestureRecognizer(gestureToLeft)
}


goBack(), goForward() 以外の処理を追加したいときや、canGoBack(), canGoForward() が false のときに何か処理を加えたいとき、target を self にして呼び出すメソッドを用意する


ViewController.swift

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
...
self.setupSwipeGestures()
}

func setupSwipeGestures() {
// 右方向へのスワイプ
let gestureToRight = UISwipeGestureRecognizer(target: self, action: "goBack")
gestureToRight.direction = UISwipeGestureRecognizerDirection.Right
self.webView.addGestureRecognizer(gestureToRight)

// 左方向へのスワイプ
let gestureToLeft = UISwipeGestureRecognizer(target: self, action: "goForward")
gestureToLeft.direction = UISwipeGestureRecognizerDirection.Left
self.webView.addGestureRecognizer(gestureToLeft)
}

func goBack() {
if (self.webView.canGoBack) {
self.webView.goBack()
} else {
// canGoBack == false の処理
}
}

func goForward() {
if (self.webView.canGoForward) {
self.webView.goForward()
} else {
// canGoForward == false の処理
}
}