以编程方式访问资产目录

我知道这是一个新的特性,这可能是不可能的,但我希望能够使用资产目录来组织我的资产,但我访问我的所有图像编程。我现在怎么访问我的图像呢?我是否仍然通过他们的文件名访问他们,如下所示:

[UIImage imageNamed:@"my-asset-name.png"];

看起来,AssetCatalog 没有引用扩展名,那么不使用“ . png”访问它会更有效吗?

我问而不是自己测试的原因是,即使删除了我的资产和资产目录,然后清除构建文件夹,我仍然可以访问我的应用程序中的资产。这阻碍了我在实现资产目录时对其进行测试。

在查看了资产目录之后,我找到了每个资产的“ Contents.json”,它的格式如下:

{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x",
"filename" : "my-asset@2x.png"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

我还是不确定我应该如何访问它,但也许这个会有帮助?

98581 次浏览

In order to access the image from the Asset Catalog, you only need to access the name of the asset group without any extensions.

So, if you add an image named @"my-button@2x.png" to the Asset Catalog, it will create an asset group called my-button.

Now, all you have to do is access the image like so:

// Objective-C
[UIImage imageNamed:@"my-button"];
// Swift
UIImage(named: "my-button")

Also, you can edit the asset group by renaming it (without renaming the images) or changing it's individual components. This will allow you to follow easier naming conventions as well as show completely different assets between different UIScreen scales without any scale checks.

In order to incorporate images for different device sizes, you may need to toggle it under the "Devices" subheading in the Asset Catalog Group's options. Here is an example of that toggle (available by right clicking the group).

@RileyE is 100% right. However, from my experiences It's also worth noting that sometimes the asset catalogue reference for the image can contain trailing white space. You probably wouldn't notice if using storyboards/xibs as the auto complete will add it. But when you reference it from code it's not so obvious what the problem is.

Swift

You can get a reference to an image in your asset catelog with

UIImage(named: "myImageName")

You don't need to include the extension.

Also Apple has added new way to get image from assets with Swift 3, It is calling as 'Image Literal' and work as below:

Image Literal