Function call order for custom UIButton with IBDesignable, IBInspectable

Starting from xcode 6 apple introduced the possibility to render your custom UIViews straight in IB. I personally love this feature because finally the interface designed in IB approaches visually what it will look like for real. Previously you had a bunch of custom UIViews in IB that ware just well… white rectangles….

This article gives some info about a custom button “HixRoundedButton” I made for one of my projects, more particular the sequence and order of the functions called in IB when rendering to screen in IB.

HixRoundedButton has the following functions:

  • Displays a rounded gradient filled rectangle as background
  • You can set an option that automatically sizes the title of the button to the max size that still fits in the button’s view

The below IB scene contains 3 such buttons (green, red and grey ones) :1

By using IBInspectable the following properties are configurable in IB:


Below you can find the code, here are some remarks about it:

  • An UIButton contains a standard UILabel “titleLabel” that holds the title. As can be seen in the apple doc, this can be accessed to configure the appearance…
  • One time configuration of this UILabel is done when added as a sub view via “didAddSubview”.
  • The title is set before the UILabel is actually on screen, this is why the check on valid window is there. Otherwise the font size would be calculated as zero and nothing is displayed. To make sure that even at first start the styling is correct, styling is also done in the “drawRect” function.
  • The “layoutSubviews” is used to make the frame of the UILabel (holding the button title) the same as the superview. Without this for some reason the frame of the UILabel would behave erratically. I believe this has something to do with the insets property of the UIButton…

Running the application in the simulator produced this:

Rendering in IB (traced this using breakpoints and debug view option)

Function call order for custom UIButton with IBDesignable, IBInspectable