我如何从NSBundle内的Assets.car(xcassets的编译版本)加载图像? (不使用CocoaPods)

问题描述 投票:5回答:3

我们收到这些错误消息:

无法加载从标识符为“ com.company.OurResourceBundle”的捆绑包中的笔尖引用的“ iconStatus”图像。

[基本上,我们将一堆图像放在xcassets文件夹中(适用于非捆绑加载的案例)。 xcassets和nib文件打包到资源束中。

启动应用程序时,

  1. nib文件中的uiimageview无法加载带有上述错误消息的任何图像。
  2. [[UIImage imageNamed:@“ OurResourceBundle.bundle / iconStatus”]返回nil

问题与“ How can I load an image from Assets.car (compiled version of xcassets) within an NSBundle?”有关,但我们不使用CocoaPods。

ios nsbundle xcasset
3个回答
9
投票

在iOS 7中,除了Xcode编译到主捆绑包之外,无法从任何.car文件加载图像。这是由Apple开发人员在https://devforums.apple.com/message/968859#968859处确认的:

不幸的是,除了Xcode编译到您的主捆绑包之外,无法从任何汽车文件加载图像,因为+ imageNamed:不接受捆绑包参数,而这样做是需要这样做的(即使如此,将只能在单个捆绑包中打开一个资产目录。

在iOS 8中,似乎有一种新方法可以执行您想要的操作:

+ (UIImage *)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle
    compatibleWithTraitCollection:(UITraitCollection *)traitCollection

0
投票

您必须定义捆绑包

  imageView.image = UIImage(named: "iconName", in: Bundle.main, compatibleWith: nil)

-1
投票

[我怀疑您的图像资产文件夹是否被压缩为.car文件,那么NSBundle将知道如何在其中搜索资产。尝试从您的资源包中创建一个新的包。然后向该捆绑包询问图像的路径。最后从该路径创建图像。这是将图像资产和本地化字符串与我们的静态库捆绑在一起时所采用的方法。我们的版本涉及更多,因为它会自动处理@ 2x和〜ipad图像之类的东西,但这是要点。

    NSBundle *myBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"your bundle" ofType:@"bundle"]];
    NSString *filePath = [myBundle pathForResource:@"icon" ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:filePath];
© www.soinside.com 2019 - 2024. All rights reserved.