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.
For Swift 4 (and 3) use this:
This approach gets the bundle universally
I was able to fix the issue getting the Interface Builder project path from the current
NSProcessInfo
object. You can then gather the correct path from theIB_PROJECT_SOURCE_DIRECTORIES
key.This technique is described in the WWDC 2014 411 session "What's New in Interface Builder" as suggested by bjhomer in this Apple Developer Forums post.
Moreover, I need to say that it was required to switch to a
UIView
subclass, because it seems that the appereance of theUIImageView
does not change in live views.This will load your IB_Designable, or if you have none - the default image.
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:
Lets pop in the swift 3 answer
For Swift 2 and Xcode 7, the interface has been changed. Should use
I use it in my project, it works fine for both IB and device.