What’s IBDesignable / IBInspectable?
IBDesignable and IBInspectable are attributes used by Interface Builder, but different than IBOutlet and IBAction that are attributes too, IBInspectable and IBDesignable are used to render elements directly in Interface Builder.
These attributes showed in WWDC 14 [1] firstly supported to Objective-C, but now you can use with Swift too.
Rendering the custom UI component
The IBDesignable attribute is responsible to identifier the class inherits from the UIView that will render in Interface Builder.
For example, I created an ImageView custom using IBDesignable:
import UIKit@IBDesignable class CustomImageView: UIImageView { override func prepareForInterfaceBuilder() {
self.layer.cornerRadius = self.bounds.size.width/2
self.layer.borderWidth = 6
self.layer.borderColor = UIColor.blackColor().CGColor
self.layer.masksToBounds = true
}
}
You can see the result bellow:
But to get this result, I need to set in Identity Inspector the UIImageView to CustomImageView:
Configuring the UI component by Interface Builder
IBInspectable is another attribute that can be used to configure your UI component (e.g.), just you need to use this attribute in your code together with the property:
@IBInspectable var borderWidth: CGFloat = 6.0 {
didSet {
self.layer.borderWidth = self.borderWidth
}
}
and the result is:
IBInspectable, unfortunately, can not use with all the types, see the list bellow that can support:
- Int
- CGFloat
- Double
- String
- Bool
- CGPoint
- CGSize
- CGRect
- UIColor
- UIImage
I would like that the next step for XCode is the possibility to create components, deliver and install it to the used inside of XCode the same form that native Apple’s components, but now, we need to use another road to share it (e.g.): GitHub [2], cocoapods [3], Carthage [4], etc…