Swift protocol to easily create reusable custom XIB-based views

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