Dismiss multiple view controllers swift - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

21 Apr 2020

Dismiss multiple view controllers swift

In order to dismiss more than one view controller, here is the small UIViewController extension that can work for many cases.

Cases like:

  • Dismiss to the particular view controller
  • Dismiss 2 or 3 or 4 or many view controllers (By count)
  • Dismiss to root view controller

Dismiss multiple view controllers swift

First of all, add this extension:

extension UIViewController {
    
    func dismissTo(vc: UIViewController?, count: Int?, animated: Bool, completion: (() -> Void)? = nil) {
        var loopCount = 0
        var dummyVC: UIViewController? = self
        for _ in 0..<(count ?? 100) {
            loopCount = loopCount + 1
            dummyVC = dummyVC?.presentingViewController
            if let dismissToVC = vc {
                if dummyVC != nil && dummyVC!.isKind(of: dismissToVC.classForCoder) {
                    dummyVC?.dismiss(animated: animated, completion: completion)
                }
            }
        }
        
        if count != nil {
            dummyVC?.dismiss(animated: animated, completion: completion)
        }
    }
    
}

Add this extension, and use it as follows...

Dismiss to particular view controller:

self.dismissTo(vc: SecondVC(), count: nil, animated: true)

Dismiss by count(1 to 100):

self.dismissTo(vc: nil, count: 3, animated: true)

Dismiss to root view controller:

self.dismissTo(vc: self.view.window?.rootViewController, count: nil, animated: true)

Finally, here is the sample project with four view controllers, download and check the example below.


No comments:

Post a Comment

Post Top Ad