简体   繁体   中英

Overriding back swipe gesture in UINavigationController

How to override gesture to pop to rootViewController, not to previous ViewController?

You can do this in a combination of the following:

Add a swipe gesture recognizer to your view controller:

在此处输入图片说明

Add the following to your view controller class:

import UIKit

class SwipeBackViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }

    @IBAction func swipeback(_ sender: UISwipeGestureRecognizer) {
        navigationController?.popToRootViewController(animated: true)
    }
}
  • The command in viewDidLoad disables the default swipe recogninzer in iOS
  • Then, the action associated with the swipe recognizer you added above handles the pop for you

My answer here goes into disabling the recognizer in more detail in case you have any questions on that.

I followed CodeBender's answer but the swipeback function didn't call.

After add self.view.addGestureRecognizer(backswipeGestureRecognizer) in viewDidLoad() , it works.

Also, you can set delegate of this gesture in viewController, in viewController's viewDidLoad. It looks like:

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController.interactivePopGestureRecognizer?.delegate = self
}

and customize it's methods in view controller. For example:

   func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive event: UIEvent) -> Bool {
    print("event \(event.description)")
    return true

}

If you set returning value for false - pop action will not be triggered

For me it worked like:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive event: UIEvent) -> Bool {
    showAlertViewController()
    return false

}

If you need this behaviour only once, you should set delegate back in viewController's deinit method

deinit {
    navigationController?.interactivePopGestureRecognizer?.delegate = navigationController
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM