Skip to content

Instantly share code, notes, and snippets.

@taglia3
Last active August 21, 2018 19:04
Show Gist options
  • Save taglia3/1fd04ca51a1b9021fd65a9366290b55a to your computer and use it in GitHub Desktop.
Save taglia3/1fd04ca51a1b9021fd65a9366290b55a to your computer and use it in GitHub Desktop.
This method allow you to go back the nearest ViewController of type T
import UIKit
extension UIViewController {
/// This method allow you to go back the nearest ViewController of type T
///
/// - Parameter type: the type of the target ViewController
/// - Returns: true if the method succeded, false if the user has to take extra actions to go back to the previous ViewController
func back<T: UIViewController>(to type: T.Type) -> Bool {
if self is T {
// the current ViewController is already the target ViewController
// no action required
return true
}
else if presentingViewController is T {
// the target ViewController is presenting the current ViewController
// we have to dismiss the current ViewController
dismiss(animated: true)
return true
}
else if navigationController?.topViewController is T {
// the current ViewController is a NavigationController
// and the topViewController is the target ViewController
// no action required
return true
}
else if let navigationController = navigationController,
let targetViewController = navigationController.viewControllers.first(where: { $0 is T }) {
// the target ViewController is the parte of the navigation stack
// of a NavigationController of the current ViewController
// we have to dismiss the current ViewController
navigationController.popToViewController(targetViewController, animated: false)
return true
}
else if (presentingViewController as? UINavigationController)?.topViewController is T {
// the target ViewController is the topViewController
// of a NavigationController that is presenting the current ViewController
// we have to dismiss the current ViewController
dismiss(animated: true)
return true
}
else if let navigationController = (presentingViewController as? UINavigationController),
let targetViewController = navigationController.viewControllers.first(where: { $0 is T }) {
// the target ViewController is the parte of the navigation stack
// of a NavigationController that is presenting the current ViewController
// we have to dismiss the current ViewController
navigationController.popToViewController(targetViewController, animated: false)
return true
}
return false
}
}
@vegeth62
Copy link

good extension...thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment