往期回顾
1. 上期图片加载的问题
观察上一期的添加图片资源方式,能够让宿主工程成功显示图片的关键是通过指定NSBundle的路径,写死图片名称

SLSearchBar.m
从这里可以发现,加载资源图片有以下问题
- 图片名称必须固定写死
- 屏幕适配,需要添加代码判断选择 @2x 和 @3x
- 不同分辨率图片会全部打包进
SLBaseKit.bundle中
2. 解决方案
思路:
- 我们熟知平常用的 @2x @3x 图片是为了缩小用户最终下载时包的大小
- 通常我们会将图片放在 .xcassets 文件中管理,新建的项目也默认创建

Images.xcassets
使用 .xcassets 优点:
- 方便在 Xcode 中查看和拖入图片
-
.xcassets最终会打包生成为Assets.car文件 - 对于
Assets.car文件,App Slicing 会为切割留下符合目标设备分辨率的图片,可以缩小用户最终下载的包的大小。
FYI: Xcode Ref Asset Catalog Format App thinning overview (iOS, tvOS, watchOS)
实际上,随着 CocoaPods 不断的更新,resource_bundles 已经可以很好的支持 .xcassets 了
操作步骤
(1)在组件模板中创建Asset Catalog

Select Asset Catalog Resource
(2)输入名称:Assets.xcassets【保持统一Apple的命名规范, 可根据自己需求修改】,然后指定存放路径

Assets.xcassets

new Assets.xcassets
(3)将图片资源拖入到Assets.xcassets,删除之前的图片资源

add png to Assets.xcassets
(4)修改代码
// NSString *searchBarImagePath = [[self currentBundle] pathForResource:@"searchbar_textfield_background@2x" ofType:@"png"];
// UIImage *searchBarImage = [UIImage imageWithContentsOfFile:searchBarImagePath];
UIImage *searchBarImage = [UIImage imageNamed:@"searchbar_textfield_background"
inBundle:[self currentBundle]
compatibleWithTraitCollection:nil];
// ...
// NSString *searchIconImagePath = [[self currentBundle] pathForResource:@"searchbar_textfield_search_icon@2x" ofType:@"png"];
// searchIcon.image = [UIImage imageWithContentsOfFile:searchIconImagePath];
searchIcon.image = [UIImage imageNamed:@"searchbar_textfield_search_icon"
inBundle:[self currentBundle]
compatibleWithTraitCollection:nil];
(5)修改SLBaseKit.podspec
# 资源文件路径
s.resource_bundles = {
# 'SLBaseKit' => ['SLBaseKit/Assets/*.png']
'SLBaseKit' => ['SLBaseKit/Assets/*.{.xcassets}']
}
(6)打开终端
pod install
(7)观察 Xcode 导航栏视图

Assets.xcassets
(8)编译 Example 工程,观察 SLBaseKit_Example.app 的包内容里的资源包

Show in Finder

open ../Products/Debug-iphoneos/SLBaseKit_Example.app/

open ../SLBaseKit_Example.app/Frameworks/SLBaseKit.framework/SLBaseKit.bundle

../SLBaseKit.bundle/Assets.car
(9)运行验证成功通过。
3. 总结
组件开发工程中,通过 .xcassets 管理图片资源,有以下几处优点
- 代码中初始化图片,不再需作屏幕适配而写死 xx@2x.png 或 xx@3x.png 的图片全名称
- 图片资源打包后统一在
Assets.car文件中,不再是散落成图片文件 - 支持 App Slicing 图片自动压缩优化,缩小用户最终下载的包的大小
- 在
Assets.xcassets可视化的设置图片的拉伸、渲染等属性 - 支持
.xib和.storyboard预览图片(这个后面会讲)