You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.5 KiB

5 years ago
  1. /*********************************************
  2. *
  3. * This code is under the MIT License (MIT)
  4. *
  5. * Copyright (c) 2016 AliSoftware
  6. *
  7. *********************************************/
  8. import UIKit
  9. // MARK: Protocol Definition
  10. /// Make your UIViewController subclasses conform to this protocol when:
  11. /// * they *are* Storyboard-based, and
  12. /// * this ViewController is the initialViewController of your Storyboard
  13. ///
  14. /// to be able to instantiate them from the Storyboard in a type-safe manner
  15. public protocol StoryboardBased: class {
  16. /// The UIStoryboard to use when we want to instantiate this ViewController
  17. static var sceneStoryboard: UIStoryboard { get }
  18. }
  19. // MARK: Default Implementation
  20. public extension StoryboardBased {
  21. /// By default, use the storybaord with the same name as the class
  22. static var sceneStoryboard: UIStoryboard {
  23. return UIStoryboard(name: String(describing: self), bundle: Bundle(for: self))
  24. }
  25. }
  26. // MARK: Support for instantiation from Storyboard
  27. public extension StoryboardBased where Self: UIViewController {
  28. /**
  29. Create an instance of the ViewController from its associated Storyboard's initialViewController
  30. - returns: instance of the conforming ViewController
  31. */
  32. static func instantiate() -> Self {
  33. let viewController = sceneStoryboard.instantiateInitialViewController()
  34. guard let typedViewController = viewController as? Self else {
  35. fatalError("The initialViewController of '\(sceneStoryboard)' is not of class '\(self)'")
  36. }
  37. return typedViewController
  38. }
  39. }