Member-only story
Using IBInspectable and IBDesignable
One (or two) of the coolest new features in recent Xcode releases are the IBInspectable properties and IBDesignable UIViews.These have nothing to do with the functionality of your application but instead impact the developer experience in Xcode. The goal is to be able to visually inspect custom views in your iOS application without running it. So assume that you have a custom view creatively named CustomView that inherits from UIView. In this custom view, it will display a string of text with a designated color. You can also choose not to display any text. We’ll need three properties:
var textColor: UIColor = UIColor.blackColor()
var text: String?
var showText: Bool = true
We can then override the drawRect function in the class:
if showText {
if let text = text {let s = NSString(string: text)
s.drawInRect(rect,withAttributes: [
NSForegroundColorAttributeName: textColor,
NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 18)!]) }}
Assuming that the text property is set, this will draw a string in the upper left hand corner of the view when the application is run. The problem is we won’t know what it looks like without running the application. This is where IBInspectable and IBDesignable come in. IBInspectable allows us to visually set property values of the view in Xcode, just like with the built in controls. IBDesignable will show us a visual preview in the storyboard. Here is how the class should look: