我有一个 iPhone 应用程序,其中我将 images
目录(组)添加到 Resources
(组)中。我想访问 images
中的图像。我需要该图像的路径,因此我创建了如下代码。
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage1" ofType:@"png" inDirectory:@"images"];
NSLog(@"%@", imagePath);
结果:
(null)
我也试过这段代码
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage1" ofType:@"png"];
但是这段代码给了我 (null)
结果。
myImage1
的路径是 Resources/images/myImage1.png
不知道是什么问题。请提出一些修复建议。
最佳答案
通过以下方法添加图片解决了我的问题。
- 右键单击 xcode 中的项目并选择
Add Files to "project name"
. - 从计算机本地磁盘中选择您的图像文件。
- 在弹出窗口中确保选择
Copy items into destination group's folder
和Create Folder References for any added folders
和Add to targets
. - 点击
Add
.
然后使用下面的代码我可以检索我的图像。
对于 Objective-C 版本
[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"png"];
对于Swift 4.0版本
Bundle.main.path(forResource: "imageName", ofType: "png")
关于iphone - 如何从主包的资源中获取图像路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16185287/