How to enable custom view properties in Xcode ?

Sometimes we need to add custom visual properties to views for our applications, for example a border-width or a corner radius. Instead of blindly setting these values in the code, Xcode allows us to add custom properties to the views and to edit them like the original properties.

Basic view

Recently I had to customize cells from a collection view: add a colored border-width and a corner radius. First, drop a UICollectionViewController object to the storyboard. This is how it appears in Xcode originally, there are only basic properties (alpha, background color, tint color)

Original collection view
Original collection view

Custom view

In order to add editable custom visual properties to a view, make a subclass of this view’s class. In our example, we create the class CustomCellView subclassing UICollectionViewCell.

Fill the class with the following code:

The magic keyword is @IBInspectable. This keyword tells Xcode that this property is editable. The IDE will add a widget to the inspector pane based on the name and the type of the property. The didSet blocks will update the view according to the property. Here is an easy example because the layer object does natively support the properties borderWidth, borderColor and cornerRadius.

Then set the custom class name to the view in the storyboard

Custom cell view.
Custom cell view.

You can see that the pane is already updated with the User Defined Runtime Attributes widgets. There are legacies from the previous versions of Xcode: do not use them, jump to the next pane and use these other widgets. This pane is updated with our custom visual properties! Xcode parses the names to readable ones, and creates input based on the type of the property, this is great!

Updated collection view.
Updated collection view.

Updated view

Now you can edit the values of the custom properties and save the storyboard, at runtime the defined properties will be reflected to your view.

There is one last thing to do, you can edit the values but the view is not updated to the view in the storyboard: the view remains blank. To fix that, you must add a second magic keyword: @IBDesignable.

This keyword tells Xcode to update the view in the editor.

Final collection view.
Final collection view.

That’s it! Xcode allows us to easily add custom visual properties!

Here it is an easy example, but you can go further and add complex properties composed of multiple subviews.

Leave a Reply

Your email address will not be published. Required fields are marked *