Swift Quick Tip —How to save time building your UI
[Before we start, this tip is aimed at developers that are using the Interface Builder.]
I’ll start with a rather regular way of implementing a UI and follow up with a simpler way to do it. Nothing like an example to get things flowing. Let’s say your team designer sets you up with a new layout, for your app’s signup screen:
Step #1
DragN’Drop
You have your SignUpViewController, but it’s bare as a baboon’s ass ... Time to drag the necessary elements, lay them out and connect the outlets:
Hmm looks similar but something doesn’t feel right 🤔
Step #2
Alter views programatically…
One option is to go to the SignupViewController and create rounded corners programatically.
Looks a lot better! However the profile image isn’t circular and doesn’t have a slight shadow either. Our designer is going to notice that for sure.
To make a perfectly round view, the corner radius has to be half the size of the the view’s height. Which, in this case, means adding the following to the viewDidLoad() method:
imgProfile.layer.cornerRadius = imgProfile.bounds.height/2
*Don’t forget to remove imgProfile from the array of views to be rounded
Now to drop shadow you’ll have to create an addShadow function and call it in viewDidLoad():
Quite a bit of work just to get the views looking as intended. What made it worse was having a view that had to be customised in a different manner from the rest.
Step #2 — Redone
The simple way
You will have to take some time to create a couple of extensions, but once they are done, every time you want to customise a UIView, it will be simple and yield immediate results.
I give you… *drum roll*
IBInspectable & IBDesignable!
IBInspectable gives you the option to alter your view from the Interface Builder directly, while IBDesignable let’s you see those changes in real-time! That’s right, no longer will you have to keep re-building and running your app just to check if the drop shadow is correct.
Time to see it in action.
Create the extensions [You can check all the code from the link at the bottom of the post]:
These extensions translate into the following on the Interface Builder:
That sums up IBInspectable, however to be able to visualize the results immediately, we’re going to have to have custom views with the @IBDesignable tag. For example, for image views:
In this case I created a Custom class for each of the different elements used in the layout (UIImageView, UITextField, UIButton & UIView), all of which are IBDesignable.
Head on over to the Interface Builder, select a view that needs to be modified and you will notice you can alter it in real time:
Now, go to the SignupViewController and delete all the new code you had added (Undo step #2 basically). If you customised your views correctly you can now run the app and see the same results as in your IB.
Example code showed in the examples:
I hope this was useful! If you enjoyed it and maybe want more, show me some love ❤