Swift Utilities : View Instantiation made Easy

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 😛 😝