iOS Tip: Using IBDesignable for previewing custom views

Xcode 6 offers you an amazing feature that help developers save A LOT of time by allowing you to preview the output even without having to run the application for your custom drawn views.

IBDesignable as it is called, when applied on your custom view allows you to preview it directly on the storyboard before you having to run the code after any change.

How?

Just prefix your custom view with IBDesignable Yes. and that’s all you need to do!! 🙂

Example

You can try this out using the iOS single view application template in Xcode.

Here’s the code within the custom UIView subclass in the file simpleView.swift.

@IBDesignable

class simpleView: UIView {
    
    // Override Draw Rect method to perform custom drawing.
    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()

        // ************************************************************
        // Paint the View Blue
        CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)  // Set fill color
        CGContextFillRect(context, rect) // Fill rectangle using the context data

        // ************************************************************
        // Paint a rect inside view Green
        let greenRect = CGRectInset(rect, 30, 30) // Inset will reduce the size of 'rect' by 30 in x and 30 in y.
        CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor) // Set fill color
        /* Fill `rect' with the current fill color. */
        CGContextFillRect(context, greenRect) // Fill rectangle using the context data
    }
}

Now you can add this view as a subview to any view in your storyboard. The changes you do in the view will immediately reflect in the storyboard (actually it still needs to build so it might take a little while ;)).

IBDesignable_AddView

Debugging with IBDesignable

Better yet, you can debug the code within your custom view class using IBDesignable without running the app. All you need to do is add/enable breakpoints in your custom view code and then select the corresponding view in storyboard and click on Xcode: Editor -> Debug Selected Views and voila! There it is.

IBDesignable_Debugging

And.. You’re welcome! 😉

Further Reads:

  1. Apple Developer: Creating a Custom View That Renders in Interface Builder
  2. Apple Developer: Debugging a Custom View Without Running Your App
  3. NSHipster: IBInspectable / IBDesignable
Advertisements

One thought on “iOS Tip: Using IBDesignable for previewing custom views

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s