【问题标题】:Load image from Bundle I get a nil从Bundle加载图像我得到一个零
【发布时间】:2019-11-30 17:05:34
【问题描述】:

当我尝试使用 NSBundle 从我的项目中获取 UIImage 时,我得到一个 nil 值。 我有图片到.xcassests

这是我从包中加载图像的代码。

- (UIImage *)imageRating:(NSString *)imageName
{
  return [UIImage imageNamed:imageName inBundle:[MyClass bundle] compatibleWithTraitCollection:nil];
}

这就是捆绑方法。

+ (NSBundle *)bundle
 {
    return [NSBundle bundleForClass:[self class]];
 }

知道为什么我得到一个 nil 值。

【问题讨论】:

    标签: ios objective-c uiimage


    【解决方案1】:

    我猜是资源路径错误。

    你的图片放在.xcassests,最后打包到.app文件中,常用main bundle。

    如果你的项目结构中包含framework,只要你在framwork中获取当前bundle,那么路径就不是主bundle下的资源,而是framwork的bundle资源。

    因为我不知道你的项目结构,下一步就是知道打印bundle的路径,并与main bundle路径比较。

    - (UIImage *)imageRating:(NSString *)imageName
    {
      NSBundle *bundle = [MyClass bundle];
      NSBundle *mainBundle = [NSBundle mainBundle];
      NSLog(@"bundle: %@\n main bundle: %@",imageBundle);
      return [UIImage imageNamed:imageName inBundle:[MyClass bundle] compatibleWithTraitCollection:nil];
    }
    

    如果路径不同,有两种方式。

    1. 将资源以bundle的形式放到famework

    2. 将[MyClass bundle] 更改为[NSBundle mainBundle]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多