UIImage imageNamed returns nil

2020-01-24 23:08发布

I am pretty new to iOS and Xcode.

I tried to load an image with

[UIImage imageNamed:@"imageName.png/jpg and so on"];

but it only returns nil. The image should be in my project bundle, considering the fact that I can choose it from drag and drop menus in the InterfaceBuilder and it was added to Xcode via the "Add files to "projectname"..." menu.

It makes no difference whether I use .png or .jpg images, the result stays the same: they work via IB but not if I try to run the imageNamed method myself.

19条回答
看我几分像从前
2楼-- · 2020-01-24 23:22

Try re-exporting your image.

I had a similar problem, UIImage imageNamed was returning nil and none of these answers fixed my problem.

I found out that it was actually something wrong with the png file. I opened the file in GIMP image editor, saved it as a new file, exported it again as png and magically it started working.

I didn't change anything in code at all so there was definitely something wrong with the actual image file.

查看更多
爷的心禁止访问
3楼-- · 2020-01-24 23:23

In my case, using a name with accented characters proved to be a poor idea. I changed Astéroïdes to Asteroids and it worked fine.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-24 23:24

For Xcode 6.4, click on Images.xcassets and check whether there are entries for each image that you called. You may right-click on the image and select "Show in Finder" to check if the images are the correct ones added.

查看更多
再贱就再见
5楼-- · 2020-01-24 23:25

Re Mike Weller's comment. The checkbox is ....

enter image description here

查看更多
我想做一个坏孩纸
6楼-- · 2020-01-24 23:28

In my case, the PNG was malformed.

For some reason Xcode preview shown it correctly, but when I tried loading it with UIImage, it returned nil.

查看更多
贼婆χ
7楼-- · 2020-01-24 23:28

Make sure the Attributes Inspector name field of the image matches exactly the name you're using. In my case the image was part of a folder and so the image name was "folder/name". Using this long name solved the problem. XCode 7.3.1

查看更多
登录 后发表回答