Xcode6: IBDesignable and IBInspectable with Objective-C


With the release of Xcode6, Apple brought some great improvement to interface builder. With new Xcode6 now you can design custom views via Interface builder. You can achieve live rendering of custom views via IB_DESIGNABLE and IBInspectable attributes.

In this blog, I will give you an overview of IB_DESIGNABLE and IBInspectable attributes. So let’s create a demo project and follow the steps.

  • Create new Project (File > New > Project)
  • Select iOS > Application > Single View Application template.
  • Choose a template for new file (File > New > File)
  • Create new Cocoa Touch Class (iOS > Source > Cocoa Touch Class)
  • Give name to to the subclass “SAMCustomView” and subclass to UIView
  • Add IB_DESIGNABLE keyword to above the @interface in header file of the custom view. (In our case its SAMCustomView.h)
  • Add the IBInspectable to the property in the custom view class
  • Now select the Storyboard or XIB file and drag the UIView in Storyboard or XIB
  • Select the added UIView
  • Select the Identity inspector
  • Change Custom class name to SAMCustomView
  • Now select the Attribute Inspector for the added view and see the magic 🙂

Sample code will look like as follow.

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface SAMCustomView : UIView

@property (nonatomic) IBInspectable UIColor *startColor;
@property (nonatomic) IBInspectable UIColor *midColor;
@property (nonatomic) IBInspectable UIColor *endColor;
@property (nonatomic) IBInspectable NSInteger borderWidth;
@property (nonatomic) IBInspectable CGFloat cornerRadious;
@property (nonatomic) IBInspectable BOOL isHorizontal;

@end

Screenshot:

screenshot1

Currently, IBInspectable support following types.

  • Int
  • CGFloat
  • Double
  • String
  • Bool
  • CGPoint
  • CGSize
  • CGRect
  • UIColor
  • UIImage

To support older Xcode you just need to add empty macro for IBInspectable, like so:

#ifndef IBInspectable
    #define IBInspectable
#endif

If you found this useful please take a moment to share this with your friends 🙂

Get the source code on github.

Advertisements