iOS组件化 02 - 组件中图片资源管理方案优化

2019-12-31  本文已影响0人  一叶知秋的码拉松

往期回顾

iOS组件化 01 - 本地私有库的使用

1. 上期图片加载的问题

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

SLSearchBar.m

从这里可以发现,加载资源图片有以下问题

2. 解决方案

思路:

Images.xcassets

使用 .xcassets 优点:

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 管理图片资源,有以下几处优点

上一篇 下一篇

猜你喜欢

热点阅读