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.

53 lines
1.9 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 not the initialViewController of your Storyboard, but a different scene
  13. ///
  14. /// to be able to instantiate them from the Storyboard in a type-safe manner.
  15. ///
  16. /// You need to implement `sceneStoryboard` yourself to indicate the UIStoryboard this scene is from.
  17. public protocol StoryboardSceneBased: class {
  18. /// The UIStoryboard to use when we want to instantiate this ViewController
  19. static var sceneStoryboard: UIStoryboard { get }
  20. /// The scene identifier to use when we want to instantiate this ViewController from its associated Storyboard
  21. static var sceneIdentifier: String { get }
  22. }
  23. // MARK: Default Implementation
  24. public extension StoryboardSceneBased {
  25. /// By default, use the `sceneIdentifier` with the same name as the class
  26. static var sceneIdentifier: String {
  27. return String(describing: self)
  28. }
  29. }
  30. // MARK: Support for instantiation from Storyboard
  31. public extension StoryboardSceneBased where Self: UIViewController {
  32. /**
  33. Create an instance of the ViewController from its associated Storyboard and the
  34. Scene with identifier `sceneIdentifier`
  35. - returns: instance of the conforming ViewController
  36. */
  37. static func instantiate() -> Self {
  38. let storyboard = Self.sceneStoryboard
  39. let viewController = storyboard.instantiateViewController(withIdentifier: self.sceneIdentifier)
  40. guard let typedViewController = viewController as? Self else {
  41. fatalError("The viewController '\(self.sceneIdentifier)' of '\(storyboard)' is not of class '\(self)'")
  42. }
  43. return typedViewController
  44. }
  45. }