Skip to content

Instantly share code, notes, and snippets.

@lalkrishna
Created August 15, 2020 17:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lalkrishna/e3f0ecef5be315bf5ae240f09eb768f3 to your computer and use it in GitHub Desktop.
Save lalkrishna/e3f0ecef5be315bf5ae240f09eb768f3 to your computer and use it in GitHub Desktop.
UIStoryboard Extension for Easy Instantiate Viewcontrollers [Swift]
enum Storyboard: String {
case main = "Main",
onboarding = "Onboarding"
}
protocol Instantiatable {
static var storyboard: Storyboard { get }
static func instantiate() -> Self
}
extension Instantiatable where Self: UIViewController {
static func instantiate() -> Self {
// swiftlint:disable force_cast
UIStoryboard(storyboard).instantiateViewController(withIdentifier: String(describing: Self.self)) as! Self
}
}
extension UIStoryboard {
convenience init(_ storyboard: Storyboard) {
self.init(name: storyboard.rawValue, bundle: nil)
}
}
// Usage:
class ViewController: UIViewController, Instantiatable {
static var storyboard: Storyboard = .main
}
// Get Instance by:
let vc = ViewController.instantiate()
@hardikamal
Copy link

@lalkrishna Here for eq. I have to jump to ProfileVC which is in profile storyboard as well on ChatVC which is in chat storyboard. How do I achieve this?

@lalkrishna
Copy link
Author

@lalkrishna Here for eq. I have to jump to ProfileVC which is in profile storyboard as well on ChatVC which is in chat storyboard. How do I achieve this?

You have to declare both storyboard in struct and, each VC should conforms to Instantiatable protocol.

class ProfileVC: UIViewController, Instantiatable {
	static var storyboard: Storyboard = .profile
}
class ChatVC: UIViewController, Instantiatable {
	static var storyboard: Storyboard = .chat
}
let viewController = ProfileVC.instantiate()
navigationController?.pushViewController(viewController, animate: true)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment