Created
September 29, 2022 07:46
-
-
Save yucelokan/6ef010c3f1621090475914cc78d324a7 to your computer and use it in GitHub Desktop.
An extension to create an instance for UIViewController in the Storyboard.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// usage -> let viewController: ACustomViewController = UIApplication.getViewController() | |
public extension UIApplication { | |
class func getViewController<T: UIViewController>( | |
inScene named: String? = nil, | |
rootViewController: Bool = true | |
) -> T { | |
let controllerName = String(describing: T.self) | |
let storyboardName = named ?? substringStoryboardName(withViewControllerName: controllerName) | |
if rootViewController, | |
let viewController = UIStoryboard( | |
name: String(storyboardName), bundle: nil | |
).instantiateInitialViewController() as? T { | |
return viewController | |
} else if let viewController = UIStoryboard( | |
name: String(storyboardName), bundle: nil | |
).instantiateViewController(withIdentifier: controllerName) as? T { | |
return viewController | |
} else { | |
fatalError("InstantiateInitialViewController not found") | |
} | |
} | |
private class func substringStoryboardName(withViewControllerName controllerName: String) -> String { | |
let viewControllerName = controllerName | |
if let range = viewControllerName.range(of: "ViewController") { | |
return String(viewControllerName[..<range.lowerBound]) | |
} else { | |
return controllerName | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment