我正在创建一个pod,我有一个我想要使用的图像资产目录。 在我的.podspec文件中,我设置如下:
s.resource_bundles = {
'MyPodResources' => ['*.xcassets']
}
并且Images.xcassets位于pod的根目录中。
当我尝试使用imageNamed()
加载图片时,它只是无法正常工作。我没有收到错误或警告但没有显示图像。
这是有趣的部分 - 如果我尝试在示例应用程序的Main.storyboard中添加图像,我可以选择图像,它在Interface Builder中显示正常。但是,当我运行示例应用程序时,图像不可见。
我已经浏览了所有关于GH的问题但仍无法找到解决方案...这是Xcode 7 / iOS 9问题吗?
谢谢!
答案 0 :(得分:7)
最后,我为UIImage
编写了一个扩展名,并将其放在pod目录中。它看起来像这样:
class func bundledImage(named: String) -> UIImage? {
let image = UIImage(named: named)
if image == nil {
return UIImage(named: named, inBundle: NSBundle(forClass: MyBasePodClass.classForCoder()), compatibleWithTraitCollection: nil)
} // Replace MyBasePodClass with yours
return image
}
我正在使用它:
imageView.image = UIImage.bundledImage("icon-grid")
就是这样,希望有人觉得这很有用!
答案 1 :(得分:0)
在Swift 3中:
let bundle: Bundle = Bundle(identifier: "Framework Bundle ID")!
yourImageView.image = UIImage(named: "imageNameInAssets", in: bundle, compatibleWith: nil)
答案 2 :(得分:0)
我碰到了这个问题,并通过以下方法对其进行了解决。
我最初将图标图像放入Assets.xcassets中,但无法读取其中的图像。
将图标图像打包放置。创建捆绑包很容易。
s.resource_bundles = {'<YourBundleName>' => ['*.bundle']}
请注意,如果您在此处输入其他名称,则会重命名您的捆绑包!
class ImageHelper {
static func image(_ name: String) -> UIImage? {
let podBundle = Bundle(for: ImageHelper.self) // for getting pod url
if let url = podBundle.url(forResource: "<YourBundleName>", withExtension: "bundle") { //<YourBundleName> must be the same as you wrote in .podspec
let bundle = Bundle(url: url)
return UIImage(named: name, in: bundle, compatibleWith: nil)
}
return UIImage()
}
ImageHelper.image("<YourImageName>")
希望这会有所帮助。
答案 3 :(得分:0)
我遇到了同样的问题,发现了有关.podspec文件的一小段但很重要的信息
我试图使用情节提要中.xcassets内的pod捆绑包中的图像,它在情节提要中可以正常显示,但是当我运行该应用程序时,它会崩溃,提示它找不到资源。
我将podspec更改为包括s.resources
和s.resource_bundles
s.resource_bundles = {
'SDKRes' => ['SDK/Assets/*']
}
s.resources = ['SDK/Assets/*.{xcassets}']
然后它能够从情节提要中正确加载资源