从捆绑包中加载资产文件夹中的图像

11
我有一个包含资源文件夹的捆绑包。我已经阅读了关于使用UIImage(named: "drop_arrow", inBundle: bundle, compatibleWithTraitCollection: nil)(它是Swift 3的等效方式)的所有堆栈答案。
path = Bundle.main.path(forResource: "LiveUI", ofType: "bundle")
if path != nil { // path with bundle is found
     let bundle: Bundle = Bundle.init(path: path!)! // bundle is there
     let image: UIImage? = UIImage(named: "HomePlayButton", in: bundle, compatibleWith: nil)
     // HomePlayButton exists in the bundle/asset folder
     // but image is nil
}

这是我的项目结构:

enter image description here

你能看出这个项目的代码/结构有什么问题吗? 更新! ... 图像被设置为通用的所有分辨率: enter image description here

尝试使用捆绑包名称 UIImage(named: "yourbundlefile.bundle/HomePlayButton.png")! 加载此图像。 - Umesh Verma
2个回答

10

需要检查两件事情:

1)确保您的资源包中有一个带有设置了Bundle标识符的Info.plist文件。从您的截图来看,似乎并不是这种情况。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleIdentifier</key>
    <string>MyBundle</string>
</dict>
</plist>

2)确保您的捆绑包中有一个已编译的资源目录。应该命名为Assets.car。我认为Xcode不会只编译资源捆绑包内的Assets.xcassets文件夹(对于Xcode来说,捆绑包实际上是不透明的;同样它也不会编译您放在那里的任何.m源文件)。在将资产捆绑包复制到应用程序捆绑包之前,您可能需要自定义构建步骤来复制已编译的Assets.car文件到您的资产捆绑包中。

您可以通过找到您的应用程序捆绑包并右键单击它,然后选择“显示包内容”,再次右键单击其中包含的捆绑包来检查这些信息。

手动资源编译命令:

xcrun actool Images.xcassets --compile . --platform iphoneos --minimum-deployment-target 9.0

在将资源包复制到应用程序包之前,您可能需要自定义构建步骤来复制已编译的Assets.car文件到您的资源包中。您能否提供一个例子? - Andriy Savran
@TomSwift 我已经将 .xcassets 编译成 Assets.car 并放入 xxx.bundle 中,同时也将 info.plist 与 bundleIdentifier = xxx 放在了里面,但仍然无法正常工作。我是否漏掉了什么?UIImage *image = [UIImage imageNamed:@"iimageName" inBundle:bundle compatibleWithTraitCollection:nil]; - Shikha Shah
a) 添加带有 CFBundleIdentifierInfo.plist 文件,b) 手动编译资源有所帮助。 编译命令:xcrun actool Images.xcassets --compile . --platform iphoneos --minimum-deployment-target 9.0 - ph4r05

0

只是一个想法,确保捆绑包和捆绑包中的资源目录具有分配给您正在尝试加载图像的正确目标的目标成员属性(实用程序窗格 -> 目标成员资格):

Target Membership

有可能是由于某些原因,您的目标可以找到捆绑包但无法找到资产目录。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接