Swift Round UIButton Subclass IBDesignable in Interface Builder

This post walks through an easy subclass of UIButton for rendering round buttons. The implementation uses IBDesignable and IBInspectable so that the button can be fully configured in Interface Builder, without resorting to programmatic configuration.

I’ve started out with a basic Storyboard view that has only a button and label in the view, which you can see in the GitHub project (link at the end of this post).

Let’s jump right to the RoundButton subclass.

The technique for creating a round button is identical to what I used in a previous tutorial last year, except in this case the code that transforms a regular UIButton into a round button is directly in layoutSubviews of the UIButton subclass, instead of being triggered in the ViewController from the viewDidLayoutSubviews method. The advantage here is that everything is within the UIButton subclass.

To facilitate editing the button borderColor and borderWidth in Interface Builder, both properties are marked with @IBInspectable.

The cornerRadius is set intentionally in layoutSubviews to result in a round button. You could make it a property just like the color and width of the border if you wanted to allow more flexibility.

With a View containing a UIButton in the Storyboard or Xib file, you can now change the Custom Class >> Class value to RoundButton in the Identity Inspector.

Screen Shot 2016-03-16 at 3.46.44 PM

We can now show the Attributes Inspector and at the top the two new properties are visible.

Screen Shot 2016-03-16 at 3.51.26 PM

You can see that the properties from code are nicely styled in camel case. In my case, I’ve put the button on a dark background, and set the Border Color to white, while the Border Width is 2. You can play around with the values and see the button being rendered in Interface Builder as you make changes.

I’ve also set the Background and Tint properties accordingly for the button, so that in Interface Builder it looks like you see below.

Screen Shot 2016-03-16 at 3.54.43 PM

This is what it looks like when I run it and rotate to landscape mode.

Simulator Screen Shot Mar 16, 2016, 3.25.17 PM

If you want to have such a round button in your project, you can use the RoundButton class in the GitHub project here, or just create your own subclass of UIButton and copy the code.

Leave a Comment:

4 comments
Add Your Reply