AliSoftware/Reusable

Working with multiple scenes in one Storyboard

snowtema opened this issue · 2 comments

Hi!

I'm stuck with instantiating controllers from Storyboards. In my project, I have several storyboards with multiple scenes(controllers) in each storyboard.

Intro.storyboard (IntroViewController, SpalshViewController)
Main.storyboard (ViewController1, ViewController2, etc)

In my ViewController I use protocol StoryboardSceneBased, but obviously, it is not working.
Does Reusable ability to instantiate controllers like I need?

Hi

Reusable is totally able to do this, and StoryboardSceneBased is indeed intended to be used exactly instantiate controllers designed in storyboards containing multiple scenes.

As explained in the README here (don't hesitate to click on the little black triangles to open the collapsed examples in that README btw), when you're using StoryboardSceneBased, the name of the class is used by default to determine the sceneIdentifier (and not the name of the *.storyboard file), so in order for iOS to know from which *.storyboard to extract that scene/controller, you'll need to explicitly provide a value for the sceneStoryboard property in each class you mark conforming to StoryboardSceneBased.

(StoryboardSceneBased is probably the only protocol in the Reusable library where not everything in the protocol has a default implementation, so this one is not really fully a "Mixin" per-se as you still have to provide that property explicitly)


class IntroViewController: StoryboardSceneBased {
  static let sceneStoryboard = UIStoryboard(name: "Intro", bundle: nil)
}
class SplashViewController: StoryboardSceneBased {
  static let sceneStoryboard = UIStoryboard(name: "Intro", bundle: nil)
}
class ViewController1: StoryboardSceneBased {
  static let sceneStoryboard = UIStoryboard(name: "Main", bundle: nil)
}
class ViewController2: StoryboardSceneBased {
  static let sceneStoryboard = UIStoryboard(name: "Main", bundle: nil)
}

PS: Note/Tip: to avoid repeating the string literals corresponding to the storyboard names and avoid making mistakes, I recommend to either:

  1. create namespaced constants for the UIStoryboard instances, ready to use them in each ViewController's static let sceneStoryboard implementation:
enum Storyboards {
  static let intro = UIStoryboard(name: "Intro", bundle: nil)
  static let main = UIStoryboard(name: "Main", bundle: nil)
}
class IntroViewController: StoryboardSceneBased {
  static let sceneStoryboard = Storyboards.intro
}
class SplashViewController: StoryboardSceneBased {
  static let sceneStoryboard = Storyboards.intro
}
  1. Or even better, use a tool like SwiftGen to auto-generate (and auto-maintain) those at build time (which actually also generates functions and constants to instantiate Storyboard-based ViewControllers in a type-safe way too, so that's an alternative solution to Reusable for that feature.

@AliSoftware Thanks a lot for the quick feedback!