iOS Cocoapods关于s.resource_bundles&s.resources

前言

通过Cocoapods来写个自己的pod组件,如果组件需要图片、xib、storyboard等资源的时候有两种引入资源的方式分别是s.resource_bundles和s.resources

前提

Cocoapods版本

pod --version
1.8.3

Prdfile里面用了

use_frameworks!
s.resources

把资源文件都打包直接copy到Framework根目录下,这种方式pod里面的xib和storyboard可以直接引用pod里面的图片资源(xib中imageView只需设置name=0.jpg就可以显示)

  s.resources = [
    'B/Assets/**/*',
    'B/Classes/**/*.{storyboard,xib}'
  ]

目录结构如下:


目录结构

编译后效果如下:


编译后

pod里面通过代码加载资源

NSBundle *frameworkBundle = [NSBundle bundleForClass:[self class]];
GoodView *view = [frameworkBundle loadNibNamed:@"GoodView" owner:self options:nil].lastObject;
NSString *imagePath = [frameworkBundle pathForResource:@"0" ofType:@"jpg" inDirectory:nil];
UIImage *image = [UIImage imageWithContentsOfFile:
                      imagePath];

\color{red}{注意:}
如果没有用use_frameworks!的话是不会生成对应的Framework的,则直接是把资源文件直接copy到app的根目录也就是MainBundle目录(会造成和主工程资源名称重复的情况)
具体说明参考这篇博客
https://blog.csdn.net/TuGeLe/article/details/85049392

s.resource_bundles

把资源文件都打包直接copy到Framework根目录下的xx.bundle里面,这种方式pod里面的xib和storyboard无法直接引用pod里面的图片资源

s.resource_bundles = {
     'B' => ['B/Assets/*',
             'B/Classes/**/*.{storyboard,xib}']
   }

目录结构还是跟上面一样

编译后效果如下:


编译后效果
B.bundle目录

pod里面通过代码加载资源

NSBundle *frameworkBundle = [NSBundle bundleForClass:[self class]];
GoodView *view = [frameworkBundle loadNibNamed:@"B.bundle/GoodView" owner:self options:nil].lastObject;

NSString *imagePath = [frameworkBundle pathForResource:@"0" ofType:@"jpg" inDirectory:@"B.bundle"];
UIImage *image = [UIImage imageWithContentsOfFile:
                      imagePath];

这种方式在xcode的中打开xib里面图片是能正常显示的,但是项目运行起来以后会报错,图片无法加载成功

Could not load the "0.jpg" image referenced from a nib in the bundle with identifier "xxxx
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容