Pages

Tuesday 17 February 2015

IBInspectable and IBDesignable

One of the cool feature that was introduced in the Xcode 6 is enabling interface builder attributes for your custom view. i.e., the attributes that appears in the right when you click a control in the interface builder. Your custom control can have its properties right in the interface builder itself.


The closest thing you would do previously is, add your custom properties in the User defined run time attributes.
Previously, when you use a custom control, you have to do all the things by code. But now with this new feature, you can design your custom view in the interface builder itself. You can see how your custom view will appear while designing. There will be a lot of open source libraries in the future using this.
Apple have introduced two new attributes to make this happen IB_DESIGNABLE and IBInspectable. You have to prefix IB_DESIGNABLE before your custom view and add IBInspectable as the attributes to its property. So, a sample class will look like this.


The following types can be used for IBInspectable.
  • Boolean (BOOL)
  • Number (NSInteger)
  • String (NSString)
  • Localized String
  • Point (CGPoint)
  • Size (CGSize)
  • Rect (CGRect)
  • Range (NSRange)
  • Color (UIColor)
  • Image (UIImage)
The properties that have the IBInspectable attribute can be configured in the attributes inspector of the interface builder. And they will appear in the User defined run time attributesalso. They both can be used interchangeably.


You can write your code in the .m file with the IBInspectable properties setters or the drawrect method.



You can also debug your custom view without running. Simply open a assistant editor and put a breakpoint in your code and Choose Editor > Debug Selected Views.
IBInspectable can be used in your custom UIView/UIControl subclasses, categories, extensions. Don’t do expensive coding with the IBInspectable properties. The interface builder will try to compile the code no longer than 200ms. If it can’t compile within this period, the Xcode gives error.

In the first screenshot, I have added a custom text field which is of course a subclass of the UITextfiled.I can change the border color of the text field from the interface builder itself.

The apple docs is here and the sample source code is in the github.




Grap the code and play around yourself and make some useful controls with this. 

No comments:

Post a Comment