|
// NavigationControllerSwiftUI.swift |
|
// Created by Kanishka on 17/11/21. |
|
// More: https://bio.link/kanishka |
|
|
|
import SwiftUI |
|
import UIKit |
|
|
|
// Reference: https://stackoverflow.com/a/67495147/7992741 |
|
|
|
struct NavigationController { |
|
|
|
|
|
/// Pops the current view to the root view |
|
static func popToRootView() { |
|
findNavigationController(viewController: UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController)? |
|
.popToRootViewController(animated: true) |
|
} |
|
|
|
/// Pushes a view controller on top of the current view |
|
static func pushController(_ controller: UIViewController){ |
|
findNavigationController(viewController: UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController)!.pushViewController(controller, animated: true) |
|
} |
|
|
|
/// Allows a function to do actions with the current navigation controller |
|
static func navigationAction(_ action: ((UINavigationController)->())) { |
|
action(findNavigationController(viewController: UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController)!) |
|
|
|
} |
|
|
|
|
|
/// Goes through the application window to find the navigation controller |
|
static private func findNavigationController(viewController: UIViewController?) -> UINavigationController? { |
|
guard let viewController = viewController else { |
|
return nil |
|
} |
|
|
|
if let navigationController = viewController as? UINavigationController { |
|
return navigationController |
|
} |
|
|
|
for childViewController in viewController.children { |
|
return findNavigationController(viewController: childViewController) |
|
} |
|
|
|
return nil |
|
} |
|
} |
|
|
|
extension UIApplication { |
|
|
|
var keyWindow: UIWindow? { |
|
return UIApplication.shared.connectedScenes |
|
.filter { $0.activationState == .foregroundActive } |
|
.first(where: { $0 is UIWindowScene }) |
|
.flatMap({ $0 as? UIWindowScene })?.windows |
|
.first(where: \.isKeyWindow) |
|
} |
|
|
|
} |