[英]UIImage load wrong image in main bundle
我有一个包含 10 多个包的主项目。 我有两个名为map_bubble_right_normal
图像,一个在主包中,另一个在子包(SCommon.bundle)中。 我写的代码如下:
UIImage *image = [UIImage imageNamed:@"map_bubble_right_normal"];
该代码已经写didFinishLaunchingWithOptions
的AppDelegate
。
我想加载我保存在主包中的图像。 但是,从子包(SCommon.bundle)加载图像的代码的结果。
我猜保存在主包中的图像可能是错误图像(可能是复制问题)。 因此,我显示 ipa 内容以查看保存在根目录下的“map_bubble_right_normal”文件。 图是对的!!!!!
我不知道为什么imageNamed:
会从子包(SCommon.bundle)加载图像。 我尝试删除应用程序并重新启动 iPhone,结果是一样的。 而且,我尝试删除 XCode 的派生数据,并清理项目。 图像仍然从子包(SCommon.bundle)加载。
另外,我在 iOS 8 和 iOS 9 设备上测试了这个问题。
到目前为止,只有更改 bundleId(main bundle) 的方法可以暂时解决问题。
我知道 UIImage 的缓存功能,但我不明白为什么会发生奇怪的场景。
真心求大神帮忙。 谢谢~
谢谢大家的回答。 我很抱歉误导了我们所有人。
我找到了问题的原因。 错误图像不是来自 Assets.car 的子包。 问题的原因实际上应该归咎于物理目录中的Image.assert。 CocoaPods 会将所有匹配的“*.assets”复制到 Assets.car。
我在Apple Developer forum提出了同样的问题,并找到了问题的关键提示。
Cocoapods 的问题相对于问题Pods 复制资源脚本覆盖了默认的 xcasset bahaviour 。
如果您的 Pod Repo 添加了名称与*.xcassets
匹配的任何文件夹,Pod_resources.sh 脚本将复制*.xcassets
中的每个*.xcassets
。
Pod_resources.sh 的关键代码:
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ]
...
# Find all other xcassets (this unfortunately includes those of path pods and other targets).
OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d)
while read line; do
if [[ $line != "`realpath $PODS_ROOT`*" ]]; then
XCASSET_FILES+=("$line")
fi
...
fi
如果您的 Pod 添加了任何xcassets
文件,则条件XCASSET_FILES
将被满足。
要从主包加载图像,试试这个:
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"map_bubble_right_normal" ofType:@"png"]];
如果您想从 mainBundle 加载,请尝试以下代码:
NSBundle* myBundle = [NSBundle mainBundle];
NSString* myImage = [myBundle pathForResource:@"Seagull" ofType:@"jpg"];
如果要从子包加载:
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"YourBundleName" ofType:@"bundle"];
NSBundle *subBundle = [NSBundle bundleWithPath:bundlePath];
NSString* myImage = [subBundle pathForResource:@"Seagull" ofType:@"jpg"];
参考这里
我也遇到过同样的情况。 而不是你上面提到的两个捆绑包,我没有显示正确名称的正确图像。 最后,我发现关键是图像的后缀是jpg
而不是png
。 我换成了png
的图像,一切都变好了。 也许这是您遇到的可能情况。 试一试,祝你好运。 :)
PS:这里有一个相关链接作为参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.