skip to Main Content

I want to check whenever the user swipes a popped viewController away. So for example when in whatsApp a user exits the current chat by swiping from the edge. How is that possible in Swift?

I don’t want to use viewDidDisappear, because this method also gets called when another viewController is presented over the current viewController.

2

Answers


  1. This "swipe" is handled by the interactivePopGestureRecognizer of the UINavigationController. It is possible to set the delegate of this gesture recognizer to your UIViewController as follows:

    navigationController?.interactivePopGestureRecognizer?.delegate = self
    

    Then, you can implement the UIGestureRecognizerDelegate in your UIViewController. This would look like this:

    extension YourViewController: UIGestureRecognizerDelegate {
        func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
            guard gestureRecognizer.isEqual(self.navigationController?.interactivePopGestureRecognizer) else { return true }
            
            print("The interactive pop gesture recognizer is being called.")
            return true
        }
    }
    

    I haven’t tested the code, but this should print every time the interactivePopGestureRecognizer is used.

    For more information, refer to the documentation of the interactivePopGestureRecognizer and UIGestureRecognizerDelegate.

    Login or Signup to reply.
  2. As I wrote in comment, a simple workaround would be in viewDidDisappear, check if the navigationController is nil.

    class MyVc: UIViewController {
    
        override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
    
            if navigationController == nil {
                print("view controller has been popped")
            }
        }
    
    }
    

    Of course, this solution works only if the view controller is embedded into a navigation controller, otherwise the if statement will always be true.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search