Swift protocol to easily create reusable custom XIB-based views

Stefano Frosoni
Jun 2, 2017 · 2 min read
Image for post
Image for post

Using a lot of custom views designed in Interface Builder on my work I found myself to rewrite the same code to instatiate a view from XIB. Then after reading some articles I find out that a protocol could be the best way to do that (it help to write less code).

Here we have the protocol:

With this protocol a custom view will automagically load its own content from the associated XIB when instantiated by the storyboard containing it, without having to write any additional code. It will be just one line of code.

A UIView subclass can conform to this protocol when is used as the XIB’s File’s Owner. The nib need the same name as the name of the class and need to be located in the bundle of that class.

How to use this:

Declare your custom view conform to the NibFileOwnerLoadable protocol.

Then you should override the init?(coder:) with loadNibContent() so that it load it's associated XIB as subviews and add constraints automatically. So supposing that your custom UIView subclass is named SearchView the code will be:

final class SearchView: UIView, NibFileOwnerLoadable {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

In the case you can’t use loadNibContent() (for example because you need a particular configuration for the subview) you can anyway use this protocol to instantiate only the XIB’s view by using instantiateFromNib() .

Thanks for your time! I hope you find this article useful.

Get in touch on Twitter: stefanofrosoni

If let swift = Programming!

A collection of posts to learn or improve your Swift skills.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store