iPhone - dismiss multiple ViewControllers

后端 未结 22 3108
粉色の甜心
粉色の甜心 2020-11-28 04:46

I have a long View Controllers hierarchy;

in the first View Controller I use this code:

SecondViewController *svc = [[SecondViewController alloc] i         


        
22条回答
  •  误落风尘
    2020-11-28 05:34

    The problem with most solutions is that when you dismiss the stack of presented viewControllers, the user will briefly see the first presented viewController in the stack as it is being dismissed. Jakub's excellent solution solves that. Here is an extension based on his answer.

    extension UIViewController {
    
        func dismissAll(animated: Bool, completion: (() -> Void)? = nil) {
            if let optionalWindow = UIApplication.shared.delegate?.window, let window = optionalWindow, let rootViewController = window.rootViewController, let presentedViewController = rootViewController.presentedViewController  {
                if let snapshotView = window.snapshotView(afterScreenUpdates: false) {
                    presentedViewController.view.addSubview(snapshotView)
                    presentedViewController.modalTransitionStyle = .coverVertical
                }
                if !isBeingDismissed {
                    rootViewController.dismiss(animated: animated, completion: completion)
                }
            }
        }
    
    }
    

    Usage: Call this extension function from any presented viewController that you want to dismiss back to the root.

    @IBAction func close() {
        dismissAll(animated: true)
    }
    

提交回复
热议问题