Swift NSBundle pathForResource() returns nil

谁都会走 提交于 2019-12-10 11:56:43

问题


I have images in my project (which is only supported on iPhones, no iPads). The images are under a group and not under images.xcassets.

I want to use the same image for all iPhones, except the @3x for the 6 Plus, so I have a structure as follows:

  Project   
        |_ Images_Group
            |
            |_ pic01@2x.png
            |_ pic01@3x.png

I am using this code to use it in my app:

if let path = NSBundle.mainBundle().pathForResource("pic01", ofType: "png") {
            image = UIImage(contentsOfFile: path)
        } 

But path always returns nil. Do I need to have pic01.png?

The image is present under Project > Build Phases > Copy Bundle Resources. What am I doing wrong?


回答1:


The tool you want here is UIImage(named:), which will look up images the way you're suggesting. pathForResource is a generic function that doesn't have special rules for images. It's looking specifically for pic01.png, which does not exist.



来源:https://stackoverflow.com/questions/30293861/swift-nsbundle-pathforresource-returns-nil

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