组件化
cocoapod
pod install
是按照 Podfile.lock里面的版本去安装,pod update
如果Podfile里面没有指定版本号的话,是按照最新的版本去安装的。
创建自己的cocoapod仓库和spec描述文件

1.创建私有远程索引仓库
-
创建私有
索引
库 托管平台。
例如:在码云上建立了一个私有索引库
image.png
-
本地添加私有远程
索引
库。
pod repo add `私有索引库的名字` `私有索引库的地址`
那么操作如下:
pod repo add NXStudySpecs https://gitee.com/Nsir/NXStudySpecs.git
通过 pod repo
可以查看当前有几个库
2. 创建工程
- 创建远程私有代码库
- 还是在码云上创建私有项目。
- 创建本地项目
-
方式一:
1.直接创建工程,把组件代码放在Class中,只要spec描述好,就会自动加载Class中组件代码
2.生成仓库的spec描述文件,指定加载组件工程的组件代码在哪。
命令:pod spec create spec文件名
-
方式二: 使用cocoapods命令:pod lib create 组件代码名称
- 这个命令会自动生成一套组件代码工程测试代码,并且有Git管理
- 还会生成podspec,描述好组件代码在哪就好.
- 如何使用自动生成的组件工程代码?
-
1. 需要把自己的组件代码放在Class中对应文件,还不够,发现根本没法引入组件代码.h文件.
2. 需要重新pod install,因为不重新pod install,Example工程根本不知道Pod更新了,pod install的作用:重新让pod库与所依赖的工程文件产生关联。

配置podspec
文件

可以使用命令
pod lib lint
检查本地是否配置正确
pod lib lint = local, pod spec lint = local/remote
提交到远程私有代码仓库。
别忘了要打上标签

把本地tag推送到远程
git push --tags
删除本地tag
git tag -d tag名

删除远程tag
git push origin --delete tag tag名 或者 :git push origin : refs/tags/tag名


3. 把自己私有代码
库的索引添加到自己私有库中:pod repo push NXStudySpecs NXStudyCategory.podspec --allow-warnings
,本地索引库就会有自己的私有库,并且远程也会有,pod repo push
会帮我们推送到远程索引库.

此时再去远程代码私有库刷新一下就可以看到了

4.划分子组件:
上面我们的私有在引用的时候会发现一些问题,如下:

在左边我们编写组件的时候分了文件夹,但是在右边测试工程引用的时候发现并没有按照我们组件的文件夹目录去分类。如果以后组件内部代码好多的时候,全都显示出来感觉就会很乱。
而且还有一个问题就是我们有时候项目只是想使用一下这个组件内部的 frame 里面的东西,不需要全部导入进来。所以这时候就需要使用subspec(子组件)去优化。
编辑podspec文件

然后更新一下索引库和代码
宿主工程使用pod update
使用最新的组件代码
pod update --no-repo-update
有时候pod search 搜不到添加的组件,解决办法如下:
输入:
rm ~/Library/Caches/CocoaPods/search_index.json
后在一次输入:pod search xxxx
skip:
组件库中含有xib文件的时候,直接引用编译会出现如下问题:

原因:
用pod导入自己创建的私有库时,如果没有添加 use_frameworks ,在编译的时候就会报 “Unable to run command 'StripNIB xx.nib' - this target might include its own product” 这个错误
需要在宿主工程添加:

然后再
pod install
就可以了
加载资源的时候:
- 之前获取都是在主bundle中:NSBundle mainBundle,但是组件资源代码,不是在主bundle中,是在自己框架的bundle中
-
获取自己bundle,[NSBundle bundleForClass:self],self:表示当前类,当前方法获取当前类所在的bundle
image.png
按照上图的格式修改私有组件的podspec配置文件如下,

然后进入Example工程重新pod install
之后,工程的目录就会如下:

这时候加载xib就不能按照之前的格式来了
之前格式:
// 注册Cell
[self.tableView registerNib:[UINib nibWithNibName:@"XMGHomeRecommendCell" bundle:nil] forCellReuseIdentifier:ID];
修改之后
// 注册Cell
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *bundleName = bundle.infoDictionary[@"CFBundleName"];
NSString *nibName = [NSString stringWithFormat:@"%@.bundle/%@",bundleName,@"XMGHomeRecommendCell"];
[self.tableView registerNib:[UINib nibWithNibName:nibName bundle:bundle] forCellReuseIdentifier:ID];
此时的xib文件加载图片的名字前面也得加上bundle名字:

参考链接
教你从 0 到 1 如何实现组件化架构
iOS组件化开发2 · 组件开发必备知识
Git & CocoaPods & 私有化,你不得不知的组件化基础!
远程私有库的资源依赖和图片使用
Tip:
项目在导入ijkplayer 等编译的时候会出现如下的错误:

解决办法,导入如下的两个库:
