Thursday, October 16, 2014

Create custom view using IBDesignable & IBInspectable in XCode6


With XCode6, Apple has added two new attributes for Interface Builder i.e. IBDesignable & IBInspectable. It allows to add controls in the Interface builder.

IBDesignable tells the interface builder that it can load the view & render it. This view should be in framework to work. 

IBInspectable will show the properties declared in custom view class in the Interface builder Inspector.

You can use these two attributes to expand the functionality of your custom view & preview the custom view directly through IB. 

In this post we will create a custom view that renders in the Interface builder.

1) Open Xcode 6 and create a single view application & select the language Swift.

2) Add new target to the project & select Framework & Library & choose Cocoa Touch Framework and named it "CustomView".





3) Create new Swift File "CustomView" subclass of UIView & add it in CustomView framework. Your Swift file look like this

import UIKit

class CustomView: UIView {

}

4) Now you need to prefix your class with keyword @IBDesignable keyword to inform the Interface builder that class will design themselves.

@IBDesignable class CustomView: UIView {

}

5) Add the properties which you want to render in the attributes Inspector of Interface builder. Here i have added 3 properties with a prefix of @IBInspectable & implement the didSet observer to update UI. This will allow the Interface builder to read & write the values of these property in the inspector.

@IBDesignable class CustomView: UIView {

@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}

6) Now open the Storyboard & add the view & change the class to CustomView.



7) Open the attribute Inspector, it will show all the properties. You can change the value of this properties & see the results.



You can download the sample app from github.


Before XCode6, we were doing all this things programatically. But now using these two keywords, we can customised the view easily & reduce the code & makes the custom view more reusable.


Note- In Objective C, you can use IB_DESIGNABLE and IBInspectable to render custom view in Interface builder.
Please check this link for more details-



2 comments:

  1. This tutorial seems good work with interface builder to reduce code for customise view.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete