Skip to content

Instantly share code, notes, and snippets.

@bnickel
Created June 29, 2017 23:48
Show Gist options
  • Save bnickel/4c4ec5f75e538d9490e43fbfb88323c0 to your computer and use it in GitHub Desktop.
Save bnickel/4c4ec5f75e538d9490e43fbfb88323c0 to your computer and use it in GitHub Desktop.
Functions that delay adding views to a navigation controller until they are removed from their parent view controllers.
func eventuallyAdd(_ viewControllers: [UIViewController], to navigationController: UINavigationController) {
if canAdd(viewControllers, to: navigationController) {
navigationController.viewControllers += viewControllers
} else {
// SHOW PLACEHOLDER CONTENT HERE IF NEEDED
DispatchQueue.main.async {
eventuallyAdd(viewControllers, to: navigationController)
}
}
}
func canAdd(_ viewControllers: [UIViewController], to: UIViewController? = nil) -> Bool {
for viewController in viewControllers where !viewController.canBeAdded(to: to) {
return false
}
return true
}
extension UIViewController {
@nonobjc func canBeAdded(to: UIViewController? = nil) -> Bool {
guard parent == nil && isViewLoaded && view.window != nil else { return true }
guard let parentViewController: UIViewController = view.superview?.nextViewController else { return true }
return parentViewController == nil || parentViewController == to
}
}
public extension UIResponder {
@nonobjc var nextViewController: UIViewController? {
guard let next = self.next else { return nil }
if let next = next as? UIViewController {
return next
} else {
return next.nextViewController
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment