从iOS 8框架加载图像

问题描述 投票:30回答:5

我正在尝试从我正在编写的iOS 8框架中加载图像(在Swift中)。我正在使用Xcode 6 Beta 6

如果图像存储在我的框架的Images.xcassets中,则此代码不起作用(即加载图像):

let image = UIImage(named: "Background.png")

如果图像存储在主机应用程序(使用框架)的Images.xcassets中,则正确加载图像(从框架内的代码中)。

我可以看到框架的Images.xcassets包含在Copy Bundle Resources阶段。

我也使用故事板文件作为框架中的资源;这适当加载。

我已经尝试重命名框架的Images.xcassets以避免与主机应用程序发生某种命名冲突,但这也不起作用。

swift ios8
5个回答
61
投票

虽然@Renatus的答案是完全有效的并且解决了核心问题(需要指定框架的捆绑包),但我想发布我使用的解决方案,因为它稍微更直接:

Swift 3.0 / 4.0 / 5.0

let image = UIImage(named: "YourImage", in: Bundle(for: YOURFRAMEWORKCLASS.self), compatibleWith: nil)

或者,您可以将此模式用于非class,即非“静态”函数:

let image = UIImage(named: "YourImage", in: Bundle(for: type(of: self)), compatibleWith: nil)

class函数的这种模式:

let image = UIImage(named: "YourImage", in: Bundle(for: self), compatibleWith: nil)

这些替代品更适合切割和粘贴。


12
投票

UIImage(名为:“Background.png”)在内部调用NSBundle.mainBundle()。因此,您的代码正在尝试在主机应用程序的包中找到资源,而不是在框架包中。要从框架的包中加载UIImage,请使用以下代码段:

let frameworkBundle = NSBundle(forClass: YOURFRAMEWORKCLASS.self)
let imagePath = frameworkBundle.pathForResource("yourImage.png", ofType: "")
if imagePath != nil {
  result = UIImage(contentsOfFile: imagePath!)
}

编辑:补充说明(thx to milz)


3
投票

在Swift 3.0中:

let currentBundle = Bundle(for: YOURCLASS.self)
guard let path = currentBundle.path(forResource: imageName, ofType: "jpg") else {  return defaultImage }
return UIImage(contentsOfFile: path) ?? defaultImage

2
投票

另一个选择是分配包标识符,这比在可读性方面分配类更有意义。

在Swift 3中:

UIImage(named: "MyImage", in: Bundle(identifier: "bundleIdentifier"), compatibleWith: nil)

0
投票

接受的答案对我不起作用。这是加载嵌入动态框架中的图像的简单方法:

    var bundle = NSBundle(forClass: self.classForCoder)

    if let bundlePath = NSBundle(forClass: self.classForCoder).resourcePath?.stringByAppendingString("/MYLIB.bundle"), resourceBundle = NSBundle(path: bundlePath) {
        bundle = resourceBundle
    }

    let image = UIImage(named: "my-embedded-image", inBundle: bundle, compatibleWithTraitCollection: nil)
© www.soinside.com 2019 - 2024. All rights reserved.