如何使用IBDesignable UIImageView在prepareForInterfaceBuilder中加载图像 [英] How to load an image in prepareForInterfaceBuilder with a IBDesignable UIImageView
问题描述
我想在IB可设计 UIImageView
中加载示例图像,以便在编辑界面时在Interface Builder中显示。以下代码不起作用,因为IB中的视图占位符保持为空(视图区域仅包含UIImageView文本):
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)
}
}
请注意:
- 在IB中,视图的自定义类类是正确的(TestImageView)
- 项目中存在Test.jpg(如果我手动设置
的图像属性UIImageView
在IB中,图像显示出来。) - 我尝试了两种不同的方法来获取代码中的包
- 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
这是使用Xcode 6 beta 3测试的。
This was tested with Xcode 6 beta 3.
更新吃了:在这两种情况下,我得到的包路径是/ Applications / Temporary / Xcode6-Beta3.app / Contents / Developer / Platforms / iPhoneSimulator.platform / Developer / Library / Xcode / Overlays
。在该路径中,图像显然不存在。
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.
推荐答案
在Swift 4.1中,@ kasplat的代码已更改为:
In Swift 4.1 the code of @kasplat has changed to:
// DYNAMIC BUNDLE DEFINITION FOR DESIGNABLE CLASS
let designTimeBundle = Bundle(for: type(of: self))
// OR ALTERNATIVELY BY PROVDING THE CONCRETE NAME OF YOUR DESIGNABLE VIEW CLASS
let designTimeBundle = Bundle(for: YourDesignableView.self)
// AND THEN SUCCESSFULLY YOU CAN LOAD THE RESSOURCE
let image = UIImage(named: "Logo", in: designTimeBundle, compatibleWith: nil)
这篇关于如何使用IBDesignable UIImageView在prepareForInterfaceBuilder中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!