The IBDesignable and IBInspectable attributes provide a great way to preview and edit custom views right in Interface builder. However, if you've tried to load resources from the bundle to render in your custom view, you might have noticed that they don't load as expected. Using a method like UIImage(named:) returns nil when your view has been compiled for interface builder.

Luckily, NSBundle offers a solution. Initializing an NSBundle instance with NSBundle(forClass:self.dynamicType) returns the correct bundle for our IBDesignable view.

Imagine for a second that we are building something like Instagram for kitten photos and we want to see what our default kitten image will look like when rendered into our custom view. Here's what that code might look like:

class CustomView: UIView {
    override func prepareForInterfaceBuilder() {
        let bundle = NSBundle(forClass: self.dynamicType)
        if let image = UIImage(named: "kitten", inBundle: bundle, compatibleWithTraitCollection: nil) {
            let imageView = UIImageView(image: image)
            imageView.frame = self.bounds

Now can we please see the kitten you ask? Well, alright then:

Kitten screenshot