Xcode 6 iOS 8 UIImage imageNamed from bundle issue

2019-05-06 12:33发布

问题:

I build my project using iOS 7.1 and try to load UIImage view with image that is stored in the /images/cars/car_1.png

All images are located in the folder images as on picture below in project tree:

So it works perfect for iOS 7.1 and Xcode 5, but when I try to use Xcode 6 and iOS 8 the UIImage instance is equal nil when I try crate image.

UIImage *image = [UIImage imageNamed:@"/images/cars/car_1.png"];

po image

nil (for iOS 8)

it can be also

UIImage *image = [UIImage imageNamed:@"/images/sport-cars/car_1.png"];

as you can see the name of resources is the same car_1.png but it is ok because they are in different resources folders not in the bundle folders.

回答1:

Ok the problem is that on the simulator and seems on the device as well by some reason when we use @"/Reference Folder Path/image.jpg" it won't work.

Removing this "/" at start of path solve this issue.

You can check this video to see how it works.



回答2:

On iOS 4 and later, if the file is in PNG format, it is not necessary to specify the .PNG filename extension. Prior to iOS 4, you must specify the filename extension.

So the answer is you have to specify the filename extension for all JPEG.

If this not solve your problem, Try this

Instead of using the imageNamed you can load the image with the methods imageWithContentsOfFile

NSString *imageFile = [NSString stringWithFormat:@"%@/iphone4/%@", [[NSBundle mainBundle] resourcePath], @"1.png"];
UIImage* image = [UIImage imageWithContentsOfFile:imageFile];

NSString *imageFile1 = [NSString stringWithFormat:@"%@/iphone5/%@", [[NSBundle mainBundle] resourcePath], @"1.png"];
UIImage* image1 = [UIImage imageWithContentsOfFile:imageFile1];

NSString *imageFile2 = [NSString stringWithFormat:@"%@/iphone6/%@", [[NSBundle mainBundle] resourcePath], @"1.png"];
UIImage* image2 = [UIImage imageWithContentsOfFile:imageFile2];

I have added 3 folders (with same image name and extension) in my project. I am able to fetch them differently and it work fine