模块化-Pod本地库间资源文件访问

在进行组件化或者打静态库时,不可避免的会进行资源文件的处理,一般有以下几种情况:

1、pod 库中的代码读取自身 pod 库中的资源

2、pod 库中代码读取其他 pod 库资源

3、主工程读取 pod 库资源

4、pod 库读取主工程资源(这个读取思想错误)

主工程:
通常在主工程调用主工程的资源时,可以直接 imageName 或者 [mainbundle pathForRecource] 读取,但是在 pod 进行管理的时候, pod 资源文件也会变为 bundle 加入到 mainBundle 中,但是由于最直接的 bundle 并不是 mainBundle ,所以这种方法是行不通的,关键要取到资源相关联的 bundle 。

Pod库:

一、资源文件引用的方式

CocoaPods 两种资源文件引用方式 resource_bundles & resources

image.png

recource_bundles 允许当前 Pod 库的资源包的名称和文件,key 是 bundle 的名称,value 是需要包括文件的通配。

官方推荐使用 resource_bundles ,因为用 key-value 可以避免相同名称资源的名称冲突。

建议 bundle 的名称至少包括 pod 库的名称,避免同名冲突。

s.resource_bundles = {     
     'AClassTest' => ['AClassTest/Assets/**/*{xib,xcassets,storyboard}']
     }
复制代码

recource 待研究

source_files 是否是resource的替代,有待进一步调研,这次重点recource_bundles

2. 图片资源

熟知常用的@2x @3x图片是为了缩小用户最终下载时的包的大小,通常会将图片放在 .xcassets 文件中管理,新建的项目也默认创建。

使用 .xcassets  不仅可以方便Xcode 查看和拖入图片,同时 .xcassets  最终打包生成为Assets.car 文件。对于 Assets.car 文件, App Slicing 会为切割留下符合目标设备分辨率的图片,可以缩小用户最终下载的包的大小。

对于Pods库的资源,同样也可以用 .xcassets 管理。

3. 如何获取资源
// - (UIImage *)getBundleImagel:(NSString *)imgName;

#import "LYBundle.h"

@implementation LYBundle


- (UIImage *)getBundleImagel:(NSString *)imgName{
    UIImage *image;
    
    NSBundle *mainBundle = [NSBundle bundleForClass:[self class]];
    NSBundle *resourcesBundle = [NSBundle bundleWithPath:[mainBundle pathForResource:@"LYBundle" ofType:@"bundle"]];
    if (resourcesBundle == nil) {
        resourcesBundle = mainBundle;
    }
    if (resourcesBundle) {
        image = [UIImage imageNamed:imgName inBundle:resourcesBundle compatibleWithTraitCollection:nil];
    }
    return image;
}


@end

复制代码

在其他Pod库使用的时候:

image.png

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor grayColor];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 200, 240)];
    [self.view addSubview:imgView];
    imgView.image = [[LYBundle alloc] getBundleImagel:@"adbb.jpg"];

}

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享