Skip to content

Storyboards integration

Ilya Puchka edited this page Aug 26, 2016 · 8 revisions

If you use storyboards and segues to instantiate view controllers then you don't have an option of constructor injection, because view controller instances will be created by UIKit. But you can still use property injection. To let DependencyContainer intercept the process of creating view controller and inject its properties you need to follow few steps:

  • add Dip-UI extension to your project

pod "Dip-UI" or github "AliSoftware/Dip-UI"

  • in Interface Builder set a user-defined attribute for view controller where you want to inject properties to with name dipTag and some unique value

  • when you configure container you need to register view controller using the tag value that you used for dipTag attribute in Interface Builder. Provide resolveDependencies block that will perform property injection (you can also use auto-injection)
container.register(tag: "myVC") { MyViewController() }
  .resolvingProperties { container, controller in ... }
  • set the container as the one to be used for components created from storyboard (you can use it not only for view controllers but for any NSObject that you put on storyboard)
DependencyContainer.uiContainers = [container]
  • make your view controller to conform to StoryboardInstantiatable. You don't need to add anything to conform to this protocol, because Dip-UI already provides the default implementation for NSObject (check Dip-UI readme for more info about StoryboardInstantiatable).
extension MyViewController: StoryboardInstantiatable { }

Tip: You can use Nil type for dipTag and register view controller without tag.