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条回答
smile是对你的礼貌
2楼-- · 2020-01-24 23:30

If you verified all of the above and are finding that your UIImage(named: "myImage") returns nil from code inside of a dynamic framework you are building, then you have to change the code to:

UIImage(named: "myImage", in: Bundle(identifier: "com.myframework.name"), compatibleWith: nil)

This should retrieve the asset from CXAssets correctly.

查看更多
倾城 Initia
3楼-- · 2020-01-24 23:32

Make sure you have the image for the DEVICE you are using in your .xcassets file. An image flagged for iPad won't show up on the phone (or the simulated phone).

查看更多
看我几分像从前
4楼-- · 2020-01-24 23:33

Check that file has no space at the end. The name like name @2x.png will fail loading, but name@2x.png is fine

查看更多
祖国的老花朵
5楼-- · 2020-01-24 23:33

Swift 5

If you get UIImage nil in dynamic framework, you should set image with bundle identifier.

You can create extension for Bundle like this;

  • Create extension;

    extension Bundle { public static let myFramework = Bundle(identifier: "com.myFramework.bundle") }

  • Then use like this;

    UIImage(named: "myImageName", in: Bundle.myFramework, compatibleWith: nil)

Or

You can use like this;

  • UIImage(named: "myImageName", in: Bundle(for: type(of: self)), compatibleWith: nil)

I think the first one is useful because it's more readable than second one.

Enjoy

查看更多
迷人小祖宗
6楼-- · 2020-01-24 23:36

I just had this issue for jpg files named on disk "file.jpg"

I was trying to load without the extension, just @"file". While this works fine for pngs, it does not for jpg. Once I used @"file.jpg", it worked!

查看更多
smile是对你的礼貌
7楼-- · 2020-01-24 23:37

i had a similar issue, finally the cleanup fixed it: the image showed up in the simulator, but id did not show up when running the app on the iPhone.
What I did: 1) deleted the app from the iPhone 2) performed Product/Clean after that the bug was fixed and the image showed up!

查看更多
登录 后发表回答