Swift Utilities : View Instantiation made Easy

Shrinivas Prabhu
Sep 4, 2018 · 2 min read

I will be presenting a series of article in this section so as to create utility classes/ functions which will be handy during development, lets start with view instantiation

During iOS app development its a common usecase to instantiate views
Generally we can instantiate view in 3 ways

  • Instantiating using xib
  • Instantiating using storyboard
  • Programmatically creating view and adding constraints

The last one is out of scope of this article.

Instantiating using xib
We have to instantiate xib from main bundle and load it. In this case the code will look something like this

Instantiating using storyboard
Here we instantiate storyboard and then load the viewController using its identifier. A sample can be seen as follows

So above implementation works perfectly, the only drawback being we have to copy paste above lines of code every time we need to instantiate a new viewcontroller . A Simpler way will probably be generalising above approach to get view on passing variable arguments

Proceeding further we can generalise above approach so that we need not copypaste the same code every time we need to instantiate a view.

Kindly import code from following repo where I have attempted to do it.

After this step instantiation of view will be piece of cake. View instantiation can be done as follows

  • Instantiating using xib : Conform xibbable protocol to view or viewcontroller having xib and view can be instantiated as follows
  • Instantiating using storyboard : Conform storyboardable protocol to viewcontroller and pass storyboard name as argument

P.S : For using the above repo filename, classname, xib name should be kept same else it will not work. Similarly identifier be same as class name in case of story board

So this way redundant code can be reduced to a great extent. Kindly share your views on this.

Happy coding !!!!

Thanks Ganesh & Karthik for proofreading. Now we know whom to blame for any typos 😛 😝

Shrinivas Prabhu

Written by

iOS Developer, Swift fan, tech enthusiast , curious learner, movie freak

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