【问题标题】:Load image from iOS 8 framework从 iOS 8 框架加载图像
【发布时间】:2014-09-09 08:18:41
【问题描述】:

我正在尝试从我正在编写的 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


    【解决方案1】:

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

    斯威夫特 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)
    

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

    【讨论】:

    • 为我工作,但最好详细说明 YOURFRAMEWORKCLASS 的含义。我最初尝试了伞头,但没有用,所以我用框架的主入口点类替换了它......这有效。
    • 谢谢你,你救了我的命!
    【解决方案2】:

    UIImage(named: "Background.png") 在内部调用 NSBundle.mainBundle()。因此,您的代码正在尝试在主机应用程序包中查找资源,而不是在框架包中。要从框架的包中加载 UIImage,请使用这个 sn-p:

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

    已编辑:添加说明(感谢 milz)

    【讨论】:

    • 虽然您的回答可能会解决问题,但最好能说明问题所在以及您的回答如何解决问题。这是进一步改进这个和未来答案的建议。
    • 您可能不应该在此处使用带有扩展名的图像名称 yourImage.png - 您希望 UIKit 在 @2、@3 等之间进行选择。
    【解决方案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
    

    【讨论】:

      【解决方案4】:

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

      Swift 3 中:

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

      【讨论】:

        【解决方案5】:

        接受的答案对我不起作用。这是加载嵌入在动态框架中的图像的一种万无一失的方法:

            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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多