iOS之组件化 三

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第16天,点击查看活动详情

资源文件的加载

图片资源

日常开发中,使用图片资源文件,都会用到UIImageimageNamed方法

self.imageView.image = [UIImage imageNamed:@"share_wechat"];
复制代码
  • 但使用的图片在组件项目中,使用这种方式是访问不到的

组件内的图片资源存储位置,在组件/Assets目录下

image-57.png 配置组件的Pod文件,写入资源的Bundle

image-58.png 在测试工程Example目录下,执行pod install

在测试工程中,通过指定Bundle访问组件内的图片资源

NSString *bundlePath = [[NSBundle bundleForClass:[self class]].resourcePath stringByAppendingPathComponent:@"/LGModuleTest.bundle"];
NSBundle *resoure_bundle = [NSBundle bundleWithPath:bundlePath];

self.imageView.image = [UIImage imageNamed:@"share_wechat" inBundle:resoure_bundle compatibleWithTraitCollection:nil];
复制代码
json文件

组件内封装HomeViewController,读取组件内的json文件

json文件的配置路径,在组件/Assets目录下

image-59.png 配置组件的Pod文件,写入资源的Bundle

image-60.png 在测试工程Example目录下,执行pod install

读取方式,指定LGHomeModule.bundle

NSString *bundlePath = [[NSBundle bundleForClass:[self class]].resourcePath stringByAppendingPathComponent:@"/LGHomeModule.bundle"];
NSString *path = [[NSBundle bundleWithPath:bundlePath] pathForResource:[NSString stringWithFormat:@"Home_TableView_Response_%@", channelId] ofType:@"json"];

NSData *data = [NSData dataWithContentsOfFile:path];
复制代码
xib文件

还有一种资源文件,和图片很相似,就是我们开发中经常用到的xib文件

访问组件内的xib文件

image-61.png 读取方式,指定Bundle

for (NSString *className in HomeTableViewCellIdentifiers.allValues) {
    
    NSString *bundlePath = [NSBundle bundleForClass:[self class]].resourcePath;

    [self.tableView registerNib:[UINib nibWithNibName:className bundle:[NSBundle bundleWithPath:bundlePath]] forCellReuseIdentifier:className];
}
复制代码

通讯解耦

同一层级的模块之间相互通讯,会导致通讯代码错综复杂。你中有我,我中有你。单一模块的修改,很可能牵扯其他模块的报错,不利于项目的维护

image-62.png 此时应该将模块之间的通讯进行下沉,抽取出一个公用的下层组件,使模块之间解耦,代码相互独立

image-63.png 针对上述的通讯解耦需求,主流解决方案可分为三种:

  • URL路由
  • target-action
  • protocol

我们在后面的文章中详细说明这几项方案。

猜你喜欢

转载自juejin.im/post/7087189214382538766
今日推荐