czane
czane

Reputation: 422

Swift4: nil loading local UIImage

read many thread on this, but no luck, so probably I am missing something here.

Receiving nil while I am loading an image on viewDidLoad()

    imageView.image = UIImage(contentsOfFile: "1.png")

Image is in Media.xcassets created for this

enter image description here Tried change 1.png in 1, tried clean, tried to close and reopen xcode. Nothing.

What I am missing here?

Upvotes: 2

Views: 1735

Answers (3)

Rawand Ahmed Shaswar
Rawand Ahmed Shaswar

Reputation: 2561

Your images are imported correctly, but your way of using them is incorrect

let sampleImage = UIImageView()
sampleImage.image = UIImage(named:"1")

And PS: you don’t need the extension names when it’s imported to the xcassets folder

Upvotes: 4

Ahmad F
Ahmad F

Reputation: 31645

When reading from the project Assets.xcassets folder, you should get the images by the name that you added to the image set, not the original name of the file(s), and that's actually so logical! Xcode should handles picking the appropriate image from the set based on what is the device (@2x, @3x...).

In your case, the name of the set is "1" thus you would get it as:

imageView.image = UIImage(named: "1")

Upvotes: 0

iGatiTech
iGatiTech

Reputation: 2268

Try setting image using below code,

imageView.image = UIImage(named: "1.png") // Extension is not required, still if you add extension then also it will work fine

OR

imageView.image = UIImage(named: "1")

Upvotes: 0

Related Questions