From 621025cef00ba42b2432c872566e19ea23aebee7 Mon Sep 17 00:00:00 2001 From: Torongo Date: Sun, 17 Mar 2024 14:18:54 +0600 Subject: [PATCH] Adding support for instantiate viewcontroller using identifier Storyboard can be instantiated using identifier. So added a defaultIdentifier that will be of format `MyViewControllerIdentifier`. --- .../Protocols/StoryboardInstantiable.swift | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/ExampleMVVM/Presentation/Utils/Protocols/StoryboardInstantiable.swift b/ExampleMVVM/Presentation/Utils/Protocols/StoryboardInstantiable.swift index b60735f..33bb51b 100755 --- a/ExampleMVVM/Presentation/Utils/Protocols/StoryboardInstantiable.swift +++ b/ExampleMVVM/Presentation/Utils/Protocols/StoryboardInstantiable.swift @@ -3,7 +3,8 @@ import UIKit protocol StoryboardInstantiable: NSObjectProtocol { associatedtype T static var defaultFileName: String { get } - static func instantiateViewController(_ bundle: Bundle?) -> T + static var defaultIdentifier: String { get } + static func instantiateViewController(_ bundle: Bundle?, _ identifier: String?) -> T } extension StoryboardInstantiable where Self: UIViewController { @@ -11,13 +12,25 @@ extension StoryboardInstantiable where Self: UIViewController { return NSStringFromClass(Self.self).components(separatedBy: ".").last! } - static func instantiateViewController(_ bundle: Bundle? = nil) -> Self { + static var defaultIdentifier: String { + return NSStringFromClass(Self.self).components(separatedBy: ".").last! + "Identifier" + } + + static func instantiateViewController(_ bundle: Bundle? = nil, _ identifier: String? = nil) -> Self { let fileName = defaultFileName let storyboard = UIStoryboard(name: fileName, bundle: bundle) - guard let vc = storyboard.instantiateInitialViewController() as? Self else { + + if let storyboardIdentifier = identifier { + guard let viewController = storyboard.instantiateViewController(withIdentifier: storyboardIdentifier) as? Self else { + fatalError("Cannot instantiate view controller \(Self.self) from storyboard with name \(fileName) using identifier \(storyboardIdentifier)") + } + return viewController + } + + guard let initialViewController = storyboard.instantiateInitialViewController() as? Self else { fatalError("Cannot instantiate initial view controller \(Self.self) from storyboard with name \(fileName)") } - return vc + return initialViewController } }