Rasto
Rasto

Reputation: 17844

Cannot load PNG image as UIImage

I am trying to load a .PNG image located in my XCode project as UIImage - but the constructor of UIImage that takes file name returns nil.

Please see the screenshot for my setup:

enter image description here

Here are some details:


EDIT: According to this blog the cause might be that workspace setup - more preciselly that the image is being loaded by framework. Not sure but in lack of better ideas I will follow this track. If you can cast some light on the matter I would by really thankful for any ideas.

Upvotes: 1

Views: 4618

Answers (3)

Rasto
Rasto

Reputation: 17844

The problem was caused by the fact that code loading the image from resources resides in framework. Main bundle does not contain resources for the framework, the corresponding bundle needs to be used. Working code:

private let imagePlaceholder = UIImage(named: "ImagePlaceholder.png", inBundle: NSBundle(forClass: CarretMoveController.self)

Upvotes: 2

codingminion
codingminion

Reputation: 411

Are these part of the images.xcassets? If not they will have to be read using NSBundle and getting a path/URL for the resource and all that and a simple filename will not suffice.

You can add the files to the assets as per the Apple documentation here. Relevant section might be the 'Adding Image Sets' one.

If you do not have images.xcassets, you can add it to your project as per one of the answers given here.

Upvotes: 1

Hashmat Khalil
Hashmat Khalil

Reputation: 1816

in your project explorer I can see that images are not named properly. it should be like this:

imagePlaceHolder.png
[email protected]

notice the png at the end of the file name, and @2x before the file extension.

Upvotes: 0

Related Questions