iPhone - dismiss multiple ViewControllers

后端 未结 22 3062
粉色の甜心
粉色の甜心 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:37

    Swift extension based upon the above answers:

    extension UIViewController {
    
        func dismissUntilAnimated(animated: Bool, viewController: T.Type, completion: ((viewController: T) -> Void)?) {
            var vc = presentingViewController!
            while let new = vc.presentingViewController where !(new is T) {
                vc = new
            }
            vc.dismissViewControllerAnimated(animated, completion: {
                completion?(viewController: vc as! T)
            })
        }
    }
    

    Swift 3.0 version:

    extension UIViewController {
    
        /// Dismiss all modally presented view controllers until a specified view controller is reached. If no view controller is found, this function will do nothing.
    
        /// - Parameter reached:      The type of the view controller to dismiss until.
        /// - Parameter flag:         Pass `true` to animate the transition.
        /// - Parameter completion:   The block to execute after the view controller is dismissed. This block contains the instance of the `presentingViewController`. You may specify `nil` for this parameter.
        func dismiss(until reached: T.Type, animated flag: Bool, completion: ((T) -> Void)? = nil) {
            guard let presenting = presentingViewController as? T else {
                return presentingViewController?.dismiss(until: reached, animated: flag, completion: completion) ?? ()
            }
    
            presenting.dismiss(animated: flag) {
                completion?(presenting)
            }
        }
    }
    

    Completely forgot why I made this as it is incredibly stupid logic considering most of the time a modal view controller's presenting view controller is UITabBarController rendering this completely useless. It makes much more sense to actually acquire the base view controller instance and call dismiss on that.

提交回复
热议问题