往期回顾
iOS组件化 01 - 本地私有库的使用
iOS组件化 02 - 组件中图片资源管理方案优化
1. 使用.xib
(1)创建一个自定义视图 SLCustomView

(2)指定代码码存放路径

(3)创建一个XIB SLCustomView.xib

(4)指定.xib
存放路径

(5)调整.xib
视图大小

(6)添加UIImageView
,设置约束

(7)添加图片资源

(8)在 xib
中设置 UIImageView
的 image

上一期中,组件中使用了
.xcassets
方式管理图片资源,这里就可以体现出优势
1> 无需指定NSBundle
路径,直接使用图片名
2> 图片可以在xib
中可视化显示
3> 下面的Storyboard同上
(9)编写代码:实例化xib视图
// SLCustomView.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface SLCustomView : UIView
+ (instancetype)customView;
@end
NS_ASSUME_NONNULL_END
// SLCustomView.m
#import "SLCustomView.h"
#define SLSearchBar_BundleName @"SLBaseKit"
@implementation SLCustomView
+ (NSBundle *)currentBundle {
static NSBundle *bundle;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:self]
pathForResource:SLSearchBar_BundleName
ofType:@".bundle"]];
if (!bundle) bundle = [NSBundle mainBundle];
});
return bundle;
}
+ (instancetype)customView {
return [[self currentBundle] loadNibNamed:NSStringFromClass(self)
owner:nil
options:nil].lastObject;
}
@end
(10)修改.podspec
,指定xib资源所在路径
s.resource_bundles = {
'SLBaseKit' => ['SLBaseKit/Assets/*.{xcassets}',
'SLBaseKit/Classes/*.{xib,nib}'] # 【注意】逗号分隔符之间不要有空格
}
(11)打开终端,执行下面命令
# 根据自己的路径修改
cd SLBaseKit/SLBaseKit/Example
pod install
(12)修改测试工程的 SLViewController.m

(13)编译测试工程,运行显示 UI
效果

2. 使用.storyboard
(1)创建首页控制器 SLHomeVC

(2)指定代码存放路径

(3)新建一个Storyboard

(4)指定 Home.storyboard
存放路径

(5)选择Home.storyboard
,添加 View Controller Scene
,并关联 SLHomeVC


(6)勾选 Is Initial View Controller

(7)编写代码
// SLHomeVC.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface SLHomeVC : UIViewController
+ (instancetype)loadStoryboard;
@end
NS_ASSUME_NONNULL_END
// SLHomeVC.m
#import "SLHomeVC.h"
#define SLSearchBar_BundleName @"SLBaseKit"
@implementation SLHomeVC
+ (NSBundle *)currentBundle {
static NSBundle *bundle;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:self]
pathForResource:SLSearchBar_BundleName
ofType:@".bundle"]];
if (!bundle) bundle = [NSBundle mainBundle];
});
return bundle;
}
+ (instancetype)loadStoryboard {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Home"
bundle:[self currentBundle]];
return storyboard.instantiateInitialViewController;
}
- (instancetype)init {
return [SLHomeVC loadStoryboard];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
(8)修改.podspec
,指定xib资源所在路径
s.resource_bundles = {
'SLBaseKit' => ['SLBaseKit/Assets/*.{xcassets}',
'SLBaseKit/Classes/*.{xib,nib,storyboard,storyboardc}'] # 【注意】逗号分隔符之间不要有空格
}
(9)打开终端,执行下面命令
# 根据自己的路径修改
cd SLBaseKit/SLBaseKit/Example
pod install
(10)修改测试工程的 SLViewController.m

(11)编译测试工程,运行成功通过
网友评论