Accessing images from nsbundle

*爱你&永不变心* 提交于 2019-12-06 14:36:14

When you use imageNamed: you must pass just a simple filename and the image must exist in the root of the app's resource bundle.

Your image is not in the root of the resource bundle, it is in a subfolder.

Since you have obtained the image's full path in the path variable, you must use the UIImage imageWithContentsOfFile: method:

self.testImageView.image = [UIImage imageWithContentsOfFile:path];

If +[UIImage imageNamed:] isn't resolving the path correctly, you could always use:

self.testImageView.image = [UIImage imageWithContentsOfFile: path];

You can just use the following:

self.testImageView.image = [UIImage imageNamed:@"MyBundle.bundle/test.png"];

But it seems that if you put the XIB in the bundle too, the interface will be relative to the bundle.

self.testImageView.image = [UIImage imageNamed:@"test.png"]

try going step by step.

First get the path to the bundle within your main bundle:

NSString *myBundlePath=[[NSBundle mainBundle] pathForResource:MyBundle ofType:@"bundle"];

Check to see if there is anything in the bundle. This is more for double checking. Once it is working you can choose to omit this code. But it is always a good idea to double check things.

 NSBundle *imageBundle=[NSBundle bundleWithPath: myBundlePath];
 NSArray *allImageURLs=[imageBundle URLsForResourcesWithExtension:@"png" subdirectory:nil];
 NSLog(@"imageURLS:  %@",allImageURLS);

Since you already have the bundle path add the image name to the path. Or you can just pull it from the list of urls that you already have in the above code.

NSString *myImagePath=[myBundlePath stringByAppendingPathComponent:@"test.png"];
NSLog(@"myImagePath=%@",myImagePath);

Then, since you have the full path, load the image

UIImage *testImage = [UIImage imageWithContentsOfFile:backgroundImagePath];

Code taken from shipping app.

Good Luck

Tim

If the images are already in the main bundle just use the image name: test.png or simply test

[UIImage imageNamed:@"test.png"];
[UIImage imageNamed:@"test"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!