How to load an image in prepareForInterfaceBuilder with a IBDesignable UIImageView
ios, swift, uiimageview
Solution
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)
Problem
I would like to load a sample image in an IB designable `UIImageView`, to be shown in Interface Builder while editing the interface. The following code does not work, as the view placeholder in IB remains empty (the view area contains only the UIImageView text): ``` @IBDesignable class TestImageView : UIImageView { override func prepareForInterfaceBuilder() { //let bundle = NSBundle.mainBundle() let bundle = NSBundle(forClass: nil) let imagePath = bundle.pathForResource("Test", ofType: "jpg") self.image = UIImage(contentsOfFile: imagePath) } } ``` Note that: - in IB the Custom Class class for the view is correct (TestImageView) - Test.jpg is present in the project (if I manually set the image property of the `UIImageView` in IB the image shows up). - I tried the two different methods of getting the bundle present in the code This was tested with Xcode 6 beta 3. Update: in both cases the bundle path I get is `"/Applications/Temporary/Xcode6-Beta3.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Overlays"`. In that path the image is obviously not present.