iOS Dev Course: How to create custom @IBDesignable UIView

Maksim Vialykh
3 min readJun 8, 2018

--

Hello, dear reader!
How to create custom UIView with IB configuration support but without massive code?

Yep! Today we’ll discover how to: create custom View, make it @IBDesignable, add @IBInspectable properties, configure view realtime in IB.

custom segment view configured in Interface Builder

Let’s getting on!

1. Create a new Cocoa Touch Class

  • Right click on project provider
New File Menu
  • Choose Cocoa Touch Class
Cocoa Touch Class
  • Enter new Class Name
Cocoa Touch Class Name

2. Add view to your storyboard/xib

  • Add new UIView
UIView component in Interface Builder
  • Setup class name
Interface Builder object class name
  • Setup Constraints
Interface Builder view constraints

Ok, we have configured view in Interface Builder. Let’s return to SegmentView class code.

3. Write @IBDesignable view code.

Custom SegmentView class code

Let’s disassemble each section.

  • Properties — all IB support properties. There are have an default value, but you can change it later in Interface builder.
  • Private properties — properties that we need in class but don’t want open to configure from outside. For example: text alignment, segment size computed property.
  • Initializers — we override initializers to configure our class components. For example UITapGestureRecognizer.
  • Actions — action to change active segment. Back to Initializers and find configure func. Here is we added gesture recognizer with selector to the action.
  • Drawing — our class used CoreGraphics powerful to draw itself components.

Ok, great! Let’s back to Interface Builder!

4. Result! Configure View in Interface Builder

Configure custom View in Interface Builder

You’ve done it!

Remember, the receipt to success is continuous learning and communication with colleagues including, self-education.

This was a small guide about @IBDesignable, @IBInspectable, custom View and setting up it in Interface Builder. Read more on Apple Developer site. Don’t stop self-education.

Subscribe to my account to get notifications about new stories.

If you still have questions — write about it in the comments. I’ll answer them in future articles.

--

--