Skip to content

Instantly share code, notes, and snippets.

@hamsternik
Last active January 24, 2019 19:55
Show Gist options
  • Save hamsternik/bf2ab86cd0f3fa3e1ccad69cb09e53bd to your computer and use it in GitHub Desktop.
Save hamsternik/bf2ab86cd0f3fa3e1ccad69cb09e53bd to your computer and use it in GitHub Desktop.
Easy storyboard & nib initialization by the concrete class from the static method
class YourCustomViewController: UIViewController {
static func storyboardInstance() -> YourCustomViewController? {
// if your storyboard's name same as VC name
let storyboard = UIStoryboard(name: String(describing: self), bundle: nil)
// make concrete storyboard as initial to use this method
// else, use instantiateViewController(withIdentifier: _ )
return storyboard.instantiateInitialViewController() as? YourCustomViewController
}
}
//============================================================================================
class LoginView: UIView {
static func nibInstance() -> LoginView? {
let nib = Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)
return nib?.first as? LoginView
}
}
@hamsternik
Copy link
Author

// More general solution

extension UIViewController {
    private class func storyboardInstancePrivate<T: UIViewController>() -> T? {
        let storyboard = UIStoryboard(name: String(describing: self), bundle: nil)
        return storyboard.instantiateInitialViewController() as? T
    }
    class func storyboardInstance() -> Self? {
        return storyboardInstancePrivate()
    }
}

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