以编程方式访问资产目录 [英] Access Asset Catalog programmatically

查看:69
本文介绍了以编程方式访问资产目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个新功能,可能无法实现,但是我很希望能够使用资产目录来组织我的资产,但是我可以通过编程方式访问所有图像.现在,我将如何访问我的图像?我是否仍按其文件名访问它们,如:

I know it's a new feature and this may not be possible, but I would love to be able to use an Asset Catalog to organize my assets, but I access all of my images programmatically. How would I access my images, now? Do I still access them by their file names like so:

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

看似,资产目录未引用该扩展名,因此如果没有".png",访问该扩展名会更有效吗?

Seemingly, the Asset Catalog doesn't reference the extension, so would it be more efficient to access it without the ".png"?

我之所以要求自己而不是自己进行测试,是因为即使删除了我的资产和资产目录,然后清理了构建文件夹,我仍然可以在应用程序中访问我的资产.实施时,这使我无法测试资产目录.

The reason I am asking instead of testing for myself is that even after removing my assets and Asset Catalog, then cleaning the build folder, I can still access my assets in my application. This is preventing me from testing the Asset Catalog, when I implement it.

浏览资产目录后,我发现了每个资产的"Contents.json",其格式如下:

After looking through the Asset Catalog, I found the "Contents.json" for each asset and it's formatted like so:

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

我仍然不确定应该如何访问它,但这也许会有所帮助吗?

I'm still unsure of how I should be accessing it, but maybe this will help?

推荐答案

要访问资产目录中的图像,只需访问资产组的名称即可,无需任何扩展名.

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

因此,如果将名为@"my-button@2x.png"的图像添加到资产目录,它将创建一个名为my-button的资产组.

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")

此外,您可以通过重命名资产组(而不重命名图像)或更改其单个组件来编辑资产组.这样一来,您就可以遵循更容易的命名约定,并显示不同UIScreen scale之间的完全不同的资产,而无需进行任何scale检查.

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.

为了合并用于不同设备尺寸的图像,您可能需要在Asset Catalog Group(资产目录组)选项中的"Devices(设备)"子标题下进行切换. 此处是该切换的示例(可通过右键单击该组来使用).

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).

这篇关于以编程方式访问资产目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆