简体   繁体   English

如何在Swift中显示UIImage

[英]How to display an UIImage in Swift

I simply would like to display an image which is part of the app. 我只是想显示一个应用程序的一部分图像。 When executing the following code, my image is nil . 执行以下代码时,我的图像nil

let image = UIImage(named: "back.png");

The "back.png" is stored in my "Images.xcassets" folder of my project. “back.png”存储在我项目的"Images.xcassets"文件夹中。

How to load the image from within the app folders? 如何从应用程序文件夹中加载图像?

(Loading the Image from a path is working for me, but I do not know how to reference an image stored in the project itself) (从路径加载图像对我有用,但我不知道如何引用存储在项目本身中的图像)

You need to use the name of the Image Set, inside Images.xcassets that back.png is stored in, instead of the actual file name. 您需要在存储了back.png Images.xcassets中使用图像集的名称,而不是实际的文件名。

在此输入图像描述

From the Asset Catalog above (obviously there would be some images in there though), you would use the code: 从上面的资产目录(显然那里会有一些图像),您将使用代码:

let image = UIImage(named: "Image")

Have a look at About Asset Catalogs for more information. 有关更多信息,请查看关于资产目录

With the latest Xcode 8.3 its much easier to adding any image, Using Image Literal option. 使用最新的Xcode 8.3,可以更轻松地添加任何图像,使用Image Literal选项。

Just select any image from assets. 只需从资产中选择任何图像。

let image = //type and select Image Literal option, and select image from as per below reference

在此输入图像描述

Don't use file extension if you place image in Images.xcassets. 如果将图像放在Images.xcassets中,请不要使用文件扩展名。 You need to use the name of the Image Set. 您需要使用图像集的名称。

let image = UIImage(named: "back")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM