接上文,创建组件与主工程完成绑定引用后,下面就需要在组件中开发需求功能。
组件的创建与绑定参考:iOS组件化开发(.a 静态库方式)
为了模拟实现,我们假定这样一个需求:
要求开发将用户信息相关的功能封装在独立组件中供其他开发使用(可能是外围开发),要求有:登录功能界面、退出功能、获取用户基础信息接口。
为此我们在组件的ToolsComponent.h中提供这些接口:
展示登录功能界面入口、退出功能接口、获取用户基础信息接口。
如下代码片段:
ToolsComponent.h
//登陆页面
+ (void)openLoginViewControllerCompleted:(void(^)(BOOLisSuccess))completed;
//获取用户基础信息
+ (void)getUserInfoCompleted:(void(^)(UserModel * model))completed;
//退出功能
+ (void)userLogoutCompleted:(void(^)(BOOL isSuccess))completed;
ToolsComponent.m中分别实现对应的功能
+ (void)openLoginViewControllerCompleted:(void(^)(BOOLisSuccess))completed{
LoginViewController * loginVc = [[LoginViewController alloc] init];
loginVc.loginFinished = completed;
UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
[nav.navigationBar setTranslucent:NO];
[nav setModalPresentationStyle:UIModalPresentationFullScreen];
[[self topMostViewController] presentViewController:nav animated:YEScompletion:NULL];
}
+ (void)getUserInfoCompleted:(void (^)(UserModel *))completed{
[UserModel loadUserDataCompleted:completed];
}
+ (void)userLogoutCompleted:(void(^)(BOOL isSuccess))completed{
[UserModel logoutCompleted:completed];
}
在具体实现的过程中,我们只需将普通项目中的MVC/MVVM等开发模式移步到组件中即可
完成组件提供的接口方法后,在Main.xcodeproj中调用ToolsComponent组件的方式有两种
1、通过ToolsComponent.h直接调用:
[ToolsComponent openLoginViewControllerCompleted:^(BOOL isSuccess) {}];
2、通过Runtime调用:
if (NSClassFromString(@"ToolsComponent")){
void(^loginResult)(BOOL isSuccess) = ^(BOOL isSuccess){};
((void(*)(id,SEL,id))objc_msgSend)(NSClassFromString(@"ToolsComponent"),NSSelectorFromString(@"openLoginViewControllerCompleted:"),loginResult);
}
Tips:Runtime 调用有风险因此需要判断组件是否存在、方法是否可用。但是使用起来会很方便无需引用太多库,可按需引用。给其他人使用静态库只需给对方提供ToolsComponent.h、libToolsComponent.a即可
在下一个更新中将会分析:
1、组件中Bundle资源文件创建及具体使用过程;
2、多个不同的组件间是如何通信、组件间功能是如何相互调用的。
上文中的代码示例在这里可以下载:
网友评论