ios – 如何使用IBDesignable UIImageView在prepareForInterfaceBuilder中加载图像

我想在IB可设计的UIImageView中加载示例图像,在界面编辑器中显示。以下代码不起作用,因为IB中的视图占位符仍然为空(视图区域仅包含UIImageView文本):

@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中,Custom Class类的视图是正确的(TestImageView)
> Test.jpg存在于项目中(如果我在IB中手动设置UIImageView的图像属性,图像显示)。
>我尝试了两种不同的方法来获取bundle中存在的代码

这是用Xcode 6 beta 3测试的。

更新:在这两种情况下,我获得的包路径是“/Applications/Temporary/Xcode6-Beta3.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Overlays”。在那条路上,图像显然不存在。

最佳答案
尝试获得类的捆绑:

let bundle = NSBundle(forClass: self.dynamicType)

或者这样指定类名

let bundle = NSBundle(forClass: TestImageView.self)

假设您的映像位于捆绑包中,例如Images.xcassets,则可以使用以下命令加载它:

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

在尝试使用它之前,请记住检查您的图像是否为零。我无法使用bundle.pathForResource获取图像路径,以正常的图像资源正常工作。也不会有UIImage调用,您只需指定名称和绑定,因此您必须使用trait集合。

这个问题与:

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

苹果响应…

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.

转载注明原文:ios – 如何使用IBDesignable UIImageView在prepareForInterfaceBuilder中加载图像 - 代码日志