From c16b40652f87476871d61050e1c345695454144a Mon Sep 17 00:00:00 2001 From: Javier Cicchelli Date: Tue, 11 Apr 2023 20:36:53 +0200 Subject: [PATCH] implemented the ModalNavigationRouter router in the Core library that inherits from the BaseNavigationRouter class. --- .../Core/Routers/ModalNavigationRouter.swift | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Apps/Locations/Libraries/Sources/Core/Routers/ModalNavigationRouter.swift diff --git a/Apps/Locations/Libraries/Sources/Core/Routers/ModalNavigationRouter.swift b/Apps/Locations/Libraries/Sources/Core/Routers/ModalNavigationRouter.swift new file mode 100644 index 0000000..b80f2df --- /dev/null +++ b/Apps/Locations/Libraries/Sources/Core/Routers/ModalNavigationRouter.swift @@ -0,0 +1,85 @@ +// +// ModalNavigationRouter.swift +// Core +// +// Created by Javier Cicchelli on 11/04/2023. +// Copyright © 2023 Röck+Cöde. All rights reserved. +// + +import UIKit + +public class ModalNavigationRouter: BaseNavigationRouter { + + // MARK: Properties + + /// The parent view controller from where this router is being called from. + public unowned let parentViewController: UIViewController + + // MARK: Initialisers + + /// Initialise this router. + /// - Parameter parentViewController: A `UIViewController` view controller instance from where this router is originated. + public init(parentViewController: UIViewController) { + self.parentViewController = parentViewController + + super.init(navigationController: .init()) + } + +} + +extension ModalNavigationRouter: Router { + public func present( + _ viewController: UIViewController, + animated: Bool, + onDismiss: OnDismissedClosure? + ) { + onDismissForViewController[viewController] = onDismiss + + if navigationController.viewControllers.isEmpty { + presentModally(viewController, animated: animated) + } else { + navigationController.pushViewController(viewController, animated: animated) + } + } + + public func dismiss(animated: Bool) { + guard let firstViewController = navigationController.viewControllers.first else { + return + } + + performOnDismissed(for: firstViewController) + + parentViewController.dismiss(animated: animated) + } + +} + +// MARK: - Helpers + +private extension ModalNavigationRouter { + + // MARK: Functions + + func presentModally(_ viewController: UIViewController, animated: Bool) { + viewController.navigationItem.leftBarButtonItem = UIBarButtonItem( + title: "Cancel", + style: .plain, + target: self, + action: #selector(onCancelPressed) + ) + + navigationController.setViewControllers([viewController], animated: false) + + parentViewController.present(navigationController, animated: animated) + } + + @objc func onCancelPressed() { + guard let firstViewController = navigationController.viewControllers.first else { + return + } + + performOnDismissed(for: firstViewController) + dismiss(animated: true) + } + +}