Xcode, iOS ナビゲーションコントローラーに右スワイプで前画面に遷移する処理を追加
こんにちわ。エンジニアの横田です。
ナビゲーションコントローラーの子コントローラーにスワイプで前画面に遷移する処理を作ってみました。
まずextensionでUIViewControllerに以下の関数を追加します。
import UIKit extension UIViewController { func addGoBackWithSwipeAction() { let swipeRightGesture: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(UIViewController.goBack)) swipeRightGesture.numberOfTouchesRequired = 1 // number of fingers swipeRightGesture.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(swipeRightGesture) } func goBack() { self.navigationController?.popViewControllerAnimated(true) } }
goBackが前画面に遷移する処理、addGoBackWithSwipeActionが呼び出し元のUIViewControllerにスワイプ処理を追加し、スワイプ時のイベントにgoBackを登録する処理です。
そして、あとは子コントローラーのviewDidLoadの中でaddGoBackWithSwipeActionを呼び出してやります。
override func viewDidLoad() { //~~~~~~~ //~~~~~~~ //スワイプして前画面アクション付与 addGoBackWithSwipeAction() //~~~~~~~ //~~~~~~~ }