Access Asset Catalog programmatically

后端 未结 4 425
青春惊慌失措
青春惊慌失措 2020-12-23 13:20

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 programmati

相关标签:
4条回答
  • 2020-12-23 13:24

    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.

    0 讨论(0)
  • 2020-12-23 13:29

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

    0 讨论(0)
  • 2020-12-23 13:29

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

    0 讨论(0)
  • 2020-12-23 13:39

    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

    0 讨论(0)
提交回复
热议问题