Reusing storyboard views (non-programmatic approach)

When it comes to reusing views many suggestions involve creating XIB files, extending the UIView class and overriding multiple initializers to load the NIB resource programmatically. There is a simpler alternative that only deals with storyboards and requires no coding whatsoever.

To get started drag a Container view from the object library and drop it inside the parent view. The container comes complete with a blank view that will serve as a slate for designing our reusable component.

The container view comes with its own segue and view controller

In order to include our reusable view inside other containers we want to refactor it onto its own storyboard file. Fortunately there is a command just for that in the Editor menu (called Refactor to storyboard). Strictly speaking this is only necessary when we have multiple parents in different storyboards themselves but I think it adds clarity regardless.

Make sure to select the child view controller before refactoring

Once in the standalone storyboard we can continue working on our view. One thing to notice is how the view keeps its own controller and doesn’t need to be constrained by a particular device aspect ratio. Auto-layout constraints are enforced as usual, something not straightforward with the traditional load from NIB approach.

Freeform simulated measures that better match our runtime are possible

To embed our view in other containers we combine again the container view object with a storyboard reference from the library pane. This time be sure to remove the empty child view and segue that come with the container view right off the bat. Then control-drag from the container onto the storyboard reference and select Embed under viewDidLoad to have the special segue recreated.

The special embed segue is triggered when the container view loads

Finally don’t forget to configure the storyboard reference on the inspector to point to our reusable component’s file.

The reusable view appears as a simple storyboard reference

That’s it, now the component will render everywhere we tell it to and layout appropriately within the container bounds.

The same component rendered twice with different positions and aspect ratios
Like what you read? Give Diego Lavalle a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.