Last active
August 7, 2019 01:41
-
-
Save ElonPark/d094c95a9591ce6c76dc45d7d45a1d92 to your computer and use it in GitHub Desktop.
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
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