How to load an image in prepareForInterfaceBuilder with a IBDesignable UIImageView

Try getting the bundle of the class like this:

let bundle = NSBundle(forClass: self.dynamicType)

or specifying the class name like this

let bundle = NSBundle(forClass: TestImageView.self)

Assuming that your image is in the bundle, for example Images.xcassets, you can then load it using:

self.image = UIImage("Test", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)

Remember to check whether your image is nil before trying to use it. I have not been able to get the image path using bundle.pathForResource to work correctly with normal image assets. There also doesn't appear to be a UIImage call where you specify just the name and bundle, so you have to use trait collection.

This question is related to:

xcode 6 IB_DESIGNABLE- not loading resources from bundle in Interface builder

Response from Apple...

Engineering has determined that this issue behaves as intended based on the following:

We can't really make this any easier than specifying the bundle. You might say, "oh, let's swizzle -[NSBundle mainBundle]", but lots of call sites that reference a bundle don't go through there (or go through the CF API). One might say then "ok, well then how about we at least swizzle -[UIImage imageNamed:]". The problem here is that there is no single replacement for the main bundle. You might have multiple live view bundles (either frameworks or apps) loaded in at once, so we can't just pick one to be the main bundle.

Developers need to be aware of bundles and how to get images from a bundle. Developers should be using UIImage(named:inBundle:compatibleWithTraitCollection:) for all image lookups.


Updated for Swift 4.2

When you instantiate an UIImage (with UIImage(named : "SomeName") the app will look for the asset in your main bundle, which works fine usually. But when you are at design time, the InterfaceBuilder holds the code of the designable views (for compiling while designing) in a separate bundle.

So the solution is: Define your bundle dynamically, hence your files can be found in design, compile and run time:

    // DYNAMIC BUNDLE DEFINITION FOR DESIGNABLE CLASS
    let dynamicBundle = Bundle(for: type(of: self))

    // OR ALTERNATIVELY BY PROVDING THE CONCRETE NAME OF YOUR DESIGNABLE VIEW CLASS
    let dynamicBundle = Bundle(for: YourDesignableView.self)

    // AND THEN SUCCESSFULLY YOU CAN LOAD THE RESSOURCE
    let image = UIImage(named: "Logo", in: dynamicBundle, compatibleWith: nil)

Lets pop in the swift 3 answer

let bundle = Bundle(for: self.classForCoder)
... UIImage(named: "AnImageInYourAssetsFolderPerhaps", in: bundle, compatibleWith: self.traitCollection)!