I have a long View Controllers hierarchy;
in the first View Controller I use this code:
SecondViewController *svc = [[SecondViewController alloc] i
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.