如何查明图像是否存在于捆绑包中?
我有一个 NSString 数组:
Flower
Car
Tree
Cat
Shoe
其中一些字符串具有与其关联的图像;有些则不然。我可以通过将 .png
附加到名称(例如 Flower.png
)来构建图像名称。
在尝试将图像加载到视图中之前,如何检查该图像是否确实存在于捆绑包中?
I have an array of NSString
s:
Flower
Car
Tree
Cat
Shoe
Some of these strings have images associated with them; some don't. I can build an image name by appending .png
to the name (e.g. Flower.png
).
How do I check whether that image actually exists within the bundle before I try to load it into the view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该也可以工作,而且有点短:
imageNamed:
方法将在主包中查找 png 文件。This should also work, and is a bit shorter:
The
imageNamed:
method will look in your main bundle for the png file.只需加载资源并检查它是否为nil:
Just load the resource and check whether it is
nil
or not:我会将图像分配为变量,然后您可以检查图像是否存在:
在接受的答案中,我们正在检查图片是否等于具有特定名称的图像。这可能会出错,因为如果
并且
我们将返回 no为图像分配一个变量,然后检查是否变量是否被分配将返回一个明确的“是”或“否”,具体取决于 Flower.png 是否存在
I would assign the image as a variable, then you can check if the image exists:
In the accepted answer we are checking to see if the picture equals an image with a specific name. This could go wrong as we will return no if
AND
Assigning a variable to the image and then checking if the variable is assigned or not will return us a definite yes or no depending on whether Flower.png exists
我什至没有将“.png”添加到文件名中,它就可以工作:
I don't even add the ".png" to the file name and it works: