lsamaria / SwipeToDismiss

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question about how to use it in a baseController

meshileya opened this issue · comments

Hello @lsamaria , thanks so much for this.

I will really appreciate knowing how possible it will be, using this same implementation in a BaseController. I don't know if you get that, pls?

Instead of having to copy codes over all the controllers to be used, let's say i have 10 Controllers in my project, is there a way i can implement this across all controllers without having to copy and paste the gesture across all the Controllers...don't know if you get that, pls.

@meshileya thanks. Just follow the 3 steps below:

1st -in my example project inside the MyController class delete the handleGesture function like so:

before deletion:

extension MyController: UIGestureRecognizerDelegate {
    
     // *** 1. you're going to delete this entire handlePanGesture function below ***
    @objc func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
        // ...
    }   
}

2nd -the entire handlePanGesture function has been deleted but MyContoller still conforms to the UIGestureRecognizerDelegate

after deletion

extension MyController: UIGestureRecognizerDelegate {
    // 2. nothing is here
}

3rd -add the deleted handlePanGesture function as an extension to the UIViewController like so:

// if you don't know what this is just copy and paste this entire thing below outside of any class

// 3. extend the UIViewController and put the handlePanGesture function there
extension UIViewController {
    
    @objc func handlePanGesture(_ gesture: UIPanGestureRecognizer) {

        let interactiveTransition = UIPercentDrivenInteractiveTransition()

        let percent = max(gesture.translation(in: view).x, 0) / view.frame.width

        switch gesture.state {

        case .began:
            navigationController?.dismiss(animated: true, completion: nil)

        case .changed:
            interactiveTransition.update(percent)

        case .ended:
            let velocity = gesture.velocity(in: view).x

            // Continue if drag more than 50% of screen width or velocity is higher than 1000
            if percent > 0.5 || velocity > 1000 {
                interactiveTransition.finish()
            } else {
                interactiveTransition.cancel()
            }

        case .cancelled, .failed:
            interactiveTransition.cancel()

        default:break
        }
    }
}

That's it. You can use use everything else from the MyController vc inside your other 9 vcs