无法在捆绑包的xcassets中加载图像

11

我需要在一个静态库中包含图片。 我创建了一个bundle并将图片插入其中,问题是如果我直接把图片放在bundle中似乎是可以工作的,但如果放在xcassets文件中就会停止工作。

我遵循了许多指南并在这个网站上搜索解决方案。最受欢迎的解决方案是插入这行代码:

[UIImage imageNamed:@"MyBundle.bundle/imageName"] 

但似乎对我不起作用

有什么想法吗?


遇到同样的问题了,你能解决吗? - BaSha
@BaSha 通过这种方法,在iOs 8上是可能的:
  • (UIImage *)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle compatibleWithTraitCollection:(UITraitCollection *)traitCollection; 在iOs 7中,最好的解决方案是从xcassets文件中删除图像。
- Serluca
谢谢,尽管我不得不单独将图像添加到捆绑包中,因为需要支持iOS 7。 - BaSha
2
@BaSha 我创建了这个类别 https://gist.github.com/serluca/e4f6a47ffbc19fccc63e 。这样,你可以使用以下代码:[NSBundle imageNamed:@"imageName"]; - Serluca
4个回答

10

有两种解决方法,

如果你的应用程序仍支持iOs 7,你可以使用这个类别: https://gist.github.com/serluca/e4f6a47ffbc19fccc63e

否则,从iOs 8开始,苹果公司提供了一种使用以下方式实现此功能的方法: + imageNamed:inBundle:compatibleWithTraitCollection: 定义在 这里


1
在Interface Builder中,您知道任何引用此内容的方法吗? - jowie
1
我尝试过了,但它指的是一个png文件,而不是.xcassets标识符。话虽如此,我没有意识到我的问题更深层次,因为它没有从我的自定义框架中导入资源。希望解决其他问题后,我会再次尝试。谢谢! - jowie
4
imageNamed:inBundle:compatibleWithTraitCollection: 可以使用嵌入在 bundle 中的 PNG 图像,但是一旦将其放入 .xcassets 文件夹中,我就找不到引用它的方法了... - jowie

8

遇到了相同的问题。看起来1-parameter imageNamed方法中XCAssets的inline bundle支持已经损坏了。不过,有一个解决办法可以使用imageNamed:inBundle:compatibleWithTraitCollection:。请注意,这只适用于iOS8!!

NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"static_lib_bundle_name" ofType:@"bundle"]];
UIImage *image  = [UIImage imageNamed:@"image_in_the_xcassets_you_want" inBundle:bundle compatibleWithTraitCollection:nil];

注意:根据苹果文档,traitCollection设置为nil,以传递主屏幕特征(如果有人知道这是什么意思,请留言!)。


3
我一直遇到同样的问题,看起来情况是这样的:Xcode将xcassets编译成二进制文件(.car)并复制到主要资源包中,这意味着xcassets不能作为绑定资源包含在内。 - Adil Soomro

3

对于Swift 2.1:

let bundle = pathToBundle // define for your app or framework
if let image = UIImage(named: "drop_arrow", inBundle: bundle, compatibleWithTraitCollection: nil) {
    // process image
}

2
我们的图片放置在Images.xcassets中,我们在IBDesignable中加载图片时遇到了问题。下面的代码解决了在Interface Builder和应用程序中预览图片的问题:
NSBundle* bundle = [NSBundle bundleForClass:[self class]];
UIImage* image = [UIImage imageNamed:@"image.jpg" inBundle:bundle compatibleWithTraitCollection:nil];

正如我所说,此方法可在iOs 8及以上版本中使用。如果您使用的是iOs 7,则可以使用我的类别 https://gist.github.com/serluca/e4f6a47ffbc19fccc63e - Serluca

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