How to load an image in prepareForInterfaceBuilder with a IBDesignable UIImageView

后端 未结 7 2239
迷失自我
迷失自我 2020-12-23 14:27

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 w

7条回答
  •  暖寄归人
    2020-12-23 15:15

    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)
    

提交回复
热议问题