Last active
April 2, 2024 09:54
-
-
Save Gurdeep0602/4fc3892c1b2861d4cd2062ddfddf3262 to your computer and use it in GitHub Desktop.
AppStoryboard enumeration
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
// | |
// AppStoryboards.swift | |
// AppStoryboards | |
// | |
// Created by Gurdeep on 15/12/16. | |
// Copyright © 2016 Gurdeep. All rights reserved. | |
// | |
import Foundation | |
import UIKit | |
enum AppStoryboard: String { | |
case Main | |
var instance : UIStoryboard { | |
return UIStoryboard(name: self.rawValue, bundle: Bundle.main) | |
} | |
func viewController<T : UIViewController>(_ viewControllerClass : T.Type, | |
_ function : String = #function, | |
_ line : Int = #line, | |
_ file : String = #file) -> T { | |
let storyboardID = (viewControllerClass as UIViewController.Type).storyboardID | |
guard let scene = instance.instantiateViewController(withIdentifier: storyboardID) as? T else { | |
fatalError("ViewController with identifier \(storyboardID), not found in \(self.rawValue) Storyboard.\nFile : \(file) \nLine Number : \(line) \nFunction : \(function)") | |
} | |
return scene | |
} | |
func initialViewController() -> UIViewController? { | |
return instance.instantiateInitialViewController() | |
} | |
} | |
extension UIViewController { | |
// Not using static as it wont be possible to override to provide custom storyboardID then | |
class var storyboardID : String { | |
return "\(self)" | |
} | |
static func instantiate(from appStoryboard: AppStoryboard, | |
function : String = #function, | |
line : Int = #line, | |
file : String = #file) -> Self { | |
return appStoryboard.viewController(self, function, line, file) | |
} | |
} |
How to prevent app crashing if view controller is not found in the storyboard which may happen if you specify incorrect storyboard?
thanks for sharing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much man! Keep up the good work!