Using IBDesignable and IBInspectable in Swift

See your stuff in the Storyboard

Photo by Molly Belle on Unsplash

Prerequisites:

Terminology

IBDesignable: An attribute that allows the Storyboard file to see and compile a custom UI element

Motivation

The Storyboard is a fantastic feature of the iOS SDK, and it allows us to see the user interface right in the Storyboard — without needing to fully compile and run a project.

A simple UIView subclass

Subclassing in Swift is actually pretty simple — as we actually get a little bit of help when we do so.

Click for Gist
Click for Gist
Click for Gist

Updating the simple UpdateCornersView class

The class created above isn’t all that useful. What about adding on useful functionality.

Click for Gist
Click for Gist

A UIView subclass with a gradient

Subclassing with a gradient is fun!

Click for Gist

Changing the background

After setting the background color, the storyboard is overriding the value. To prevent this issue, we can use func prepareForInterfaceBuilder() and set the background color, and there is an example of that shown in the following code block:

override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
backgroundColor = UIColor.red
}

Conclusion:

Yes, you can look at the completed repo to see how this can be implemented in a real project. This is an extremely important area, and creating subclasses of views is a great way of seeing how your changes will alter your project in real time. That is, with UIKit.

The Twitter contact:

Any questions? Get in touch with me on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store