Home > front end >  Check if Popped UIViewController gets dismissed by swipe
Check if Popped UIViewController gets dismissed by swipe

Time:12-22

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related