简体   繁体   中英

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 .

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

The "back.png" is stored in my "Images.xcassets" folder of my project.

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.

在此输入图像描述

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.

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. You need to use the name of the Image Set.

let image = UIImage(named: "back")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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