Chapter 36
Building Custom UI Components Using IBDesignable and IBInspectable
Some developers prefer not to use Interface Builder to design the app UI. Everything should be written in code, even for the UIs. Personally, I prefer to mix both storyboards and code together to layout the app.
But when it comes to teaching beginners how to build apps, Interface Builder is a no-brainer. Designing app UIs using Interface Builder is pretty intuitive, even for people without much iOS programming experience. One of the best features is that you can customize a UI component (e.g. button) without writing a line of code. For example, you can change the background color or font size in the Attributes inspector. You can easily turn a default button into something more visually appealing by customizing the attributes.
That said, Interface Builder has its own limitation - not all attributes of a UI object are available for configuration. Let me ask you, can you create a button like this by using Interface Builder?
To create a custom button like that, you still need to write code, or even develop your own class. This shouldn't be a big issue. But wouldn't it be great if you can design that button right in Interface Builder and view the result in real time?
IBInspectable and IBDesignable are the two keywords that make such thing possible. And, in this chapter, I will give you an introduction to both attributes and show you how to make use of them to create custom UI components.
Understanding IBInspectable and IBDesignable
In brief, IBInspectable allows you to add extra options in the Attributes inspector of Interface Builder, By indicating a class property of a UIView
as IBInspectable, the property is then exposed to the Attributes inspector as an option. And, if you indicate a UIView
class as IBDesignable, Interface Builder renders the custom view in real time. This means you can see how the custom view looks like as you edit the options.
To better understand IBInspectable and IBDesignable, let me give you an example.
To continue reading and access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.