Asset Catalogs in resource bundles

2019-03-10 23:52发布

问题:

I have a separate bundle of resources that ship with my framework. I want to put and use an asset catalog in that bundle. However UIImage imageNamed: says it uses the current apps main bundle. How do I load an image from an asset catalog in a different bundle?

The trick of using [bundle pathForResource:name ofType:@"png"] doesn't work with the compiled asset catalog. I have verified that the Assets.car file is indeed in the bundle and it contains my images.

回答1:

As of iOS 8, you can now use [UIImage imageNamed:inBundle:compatibleWithTraitCollection:] to load images by name from a different bundle. For example, a dynamic framework can use its own asset catalog separate from the main app's bundle.



回答2:

As per Apple developer:

Unfortunately it is not possible to load images from any car file aside from the one that Xcode compiles into your main bundle, as +imageNamed: does not accept a bundle parameter, which is what is needed to do so (and even then it would only be able to open a single asset catalog in a single bundle).

Here is the link:

https://devforums.apple.com/message/968859#968859



回答3:

There is a trick to make asset catalogs work with bundles: Set the resource bundle's deployment target to 6.1 (or below). Asset catalogs have only been around since 7.0, so Xcode won't actually build a .car file (compiled asset catalog) but copy the assets to the bundle directly, as documented here:

Xcode 6 provides different functionality for asset catalogs depending on > the deployment target for your project:

  • For all projects, individual images can be loaded using set names.
  • For projects with a deployment target of at least iOS 7 or OS X 10.9, Xcode compiles your asset catalogs into a runtime binary file format that reduces the download time for your app.

The caveat is that any additional information (slicing, rendering mode,...) is ignored, you only get the plain images. Although organisation via asset catalogs may be more convenient, I sense this could lead to some hard-to-find bugs/confusion...

Edit: If you apply the trick described above, you will most-likely not get the App Slicing advantages introduced with iOS 9, as after building the app, there's no compiled asset catalog but only a bunch of plain images left, so Apple will not be able to strip resources automatically. This is only an assumption though.