【问题标题】:Impossible to load an image in xcassets on bundle无法在捆绑包的 xcassets 中加载图像
【发布时间】:2014-11-27 08:00:06
【问题描述】:

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

我遵循了许多指南并在此站点上搜索了解决方案。 最流行的解决方案是插入这行代码:

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

但它似乎不适合我

有什么想法吗?

【问题讨论】:

  • 面临同样的问题,你能解决这个问题吗?
  • @BaSha 可以通过以下方法使用 iOs 8:+ (UIImage *)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle compatibleWithTraitCollection:(UITraitCollection *)traitCollection;使用 iOs 7 的最佳解决方案是从 xcassets 文件中删除图像
  • 谢谢,不过由于需要 iOS 7 支持,我不得不在捆绑包中单独添加图片
  • @BaSha 我创建了这个类别gist.github.com/serluca/e4f6a47ffbc19fccc63e。这样就可以使用after:[NSBundle imageNamed:@"imageName"];

标签: ios static-libraries nsbundle xcasset


【解决方案1】:

运行同样的问题。看起来像 1 参数 imageNamed 方法中的 XCAssets 的内联包支持被破坏了。虽然使用 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 以根据 apple docs 传递主屏幕特征(但我不太明白它的含义,如果有人知道请发表评论!)。

【讨论】:

  • 所以我遇到了同样的问题,看起来场景是 xcode 将 xcassets 直接编译为二进制文件(.car)并复制到主包中,这意味着 xcassets 不能包含在捆绑资源。 devforums.apple.com/message/968859#968859
【解决方案2】:

我们的图像被放置在 Images.xcassets 中,我们在 IBDesignable 中加载图像时遇到了问题。以下代码在 Interface builder 和应用程序中也完成了预览工作:

NSBundle* bundle = [NSBundle bundleForClass:[self class]];
UIImage* image = [UIImage imageNamed:@"image.jpg" inBundle:bundle compatibleWithTraitCollection:nil];

【讨论】:

【解决方案3】:

有两种方法可以解决这个问题,

如果您的应用仍支持 iOs 7,您可以使用此类别: https://gist.github.com/serluca/e4f6a47ffbc19fccc63e

否则,从 iOs 8 开始,Apple 添加了一种方法来执行此操作: + imageNamed:inBundle:compatibleWithTraitCollection: 定义here

【讨论】:

  • 知道如何在 Interface Builder 中引用它吗?
  • 我做了,但它指的是 png,而不是 .xcassets 标识符。话虽如此,我没有意识到,但我的问题更深一些,因为它没有从我的自定义框架中导入资产。我会在(希望)解决我的另一个问题之后再试一次。谢谢!
  • imageNamed:inBundle:compatibleWithTraitCollection: 适用于嵌入在 bundle flat 中的 PNG,但是一旦你把它放在 .xcassets 文件夹中,我就找不到引用它的方法了......跨度>
【解决方案4】:

对于 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
}

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 2021-04-23
    • 1970-01-01
    • 2016-01-15
    • 2016-12-17
    • 2017-11-01
    相关资源
    最近更新 更多