Skip to content

Instantly share code, notes, and snippets.

@ElonPark
Last active August 7, 2019 01:41
Show Gist options
  • Save ElonPark/d094c95a9591ce6c76dc45d7d45a1d92 to your computer and use it in GitHub Desktop.
Save ElonPark/d094c95a9591ce6c76dc45d7d45a1d92 to your computer and use it in GitHub Desktop.
enum AppStoryboard: String {
case main = "Main"
}
extension UIViewController {
static func instantiate<T: UIViewController>(by storyboardName: AppStoryboard) -> T? {
let type = String(describing: T.Type.self)
guard let identifier = type.components(separatedBy: ".").first else { return nil }
let storyboard = UIStoryboard(name: storyboardName.rawValue, bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: identifier)
return vc as? T
}
}
///Example
class MyViewController: UIViewController {
lazy var otherVC: OtherViewController? = UIViewController.instantiateVC(by: .main)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let vc = otherVC {
present(vc, animated: true)
}
}
}
///If always use in the view controller
extension UIViewController {
func instantiate<T: UIViewController>(by storyboardName: AppStoryboard) -> T? {
let type = String(describing: T.Type.self)
guard let identifier = type.components(separatedBy: ".").first else { return nil }
let storyboard = UIStoryboard(name: storyboardName.rawValue, bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: identifier)
return vc as? T
}
}
///Example
class MyViewController: UIViewController {
lazy var otherVC: OtherViewController? = instantiateVC(by: .main)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let vc = otherVC {
present(vc, animated: true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment