Created
August 6, 2017 07:27
-
-
Save malcolmkmd/0728a30aeadacc4319ebe3cd826bdf30 to your computer and use it in GitHub Desktop.
Storyboard identifiable
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
import UIKit | |
protocol StoryboardIdentifiable { | |
static var storyboardIdentifier: String { get } | |
} | |
extension StoryboardIdentifiable where Self: UIViewController { | |
static var storyboardIdentifier: String { | |
return String(describing: self) | |
} | |
} | |
extension UIViewController: StoryboardIdentifiable { } | |
extension UIStoryboard { | |
enum Storyboard: String { | |
case launchScreen | |
case login | |
var filename: String { | |
return rawValue.capitalized | |
} | |
} | |
convenience init(_ storyboard: Storyboard) { | |
self.init(name: storyboard.filename, bundle: Bundle.main) | |
} | |
func instantiateViewController<T: UIViewController>() -> T where T: StoryboardIdentifiable { | |
guard let viewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifier) as? T else { | |
fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifier) ") | |
} | |
return viewController | |
} | |
} | |
extension UIViewController { | |
func presentViewController(withStoryboardName storyboard: String, withIdentifier identifier: String? = nil){ | |
let sb = UIStoryboard(name: storyboard, bundle: Bundle.main) | |
var viewController: UIViewController? | |
if identifier != nil { | |
let vc = sb.instantiateViewController(withIdentifier: identifier!) | |
viewController = vc | |
}else { | |
if let initial = sb.instantiateInitialViewController(){ | |
viewController = initial | |
} | |
} | |
if viewController != nil { | |
present(viewController!, animated: true, completion: nil) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment