看了很多网上的组件化路由 , 不太理解为什么这么做 , 仿照他们的接口和调用 , 自己做了一个 , 先说下需要解决什么问题 .
在一个比较复杂的类中 , 常常某个ViewController会引入大量的其他ViewController,例如:FirstViewController会引入SecondViewController、ThirdViewController ,FourViewController。写那个#import "xxxViewController" 就很烦 . 那么就试着解决这个问题 .
给UIViewcontroller写一个类别 , 或者自己写的子类都继承一个SuperViewController . 我这里采用了类别 , 这样比较好兼容现有的项目 ,如果是新项目, 还是建议写在SuperViewController中 .
#import <UIKit/UIKit.h>
typedef void(^callBack)(id data) ;
@interface UIViewController (Router)
+ (instancetype)createViewController:(NSString *)vcName ;
+ (instancetype)createViewController:(NSString *)vcName withParameter:( NSDictionary * _Nullable )parameter ;
@property (nonatomic,copy) callBack callBack ;
+ (instancetype)viewController ;
@end
#import "UIViewController+Router.h"
#import <objc/runtime.h>
@implementation UIViewController (Router)
+ (instancetype)createViewController:(NSString *)vcName {
return [self createViewController:vcName withParameter:nil] ;
}
+ (instancetype)createViewController:(NSString *)vcName withParameter:(NSDictionary *)parameter {
Class vcClass = NSClassFromString(vcName);
UIViewController * viewController = [vcClass viewController];
[viewController setValuesForKeysWithDictionary:parameter];
NSAssert([viewController isKindOfClass: [UIViewController class]], @"传入的vcName不合法");
return viewController;
}
- (void)setCallBack:(callBack)callBack {
objc_setAssociatedObject(self, @"callBack", callBack, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (callBack)callBack {
return objc_getAssociatedObject(self, @"callBack");
}
+ (instancetype)viewController {
return [[self alloc] init];
}
@end
很简单的实现 , 调用的时候 , 由于调用的是 [vcClass viewController] , 如果写的都是从xib或者普通创建的ViewController , 类别中已经有了默认的实现 , 如果是StoryBoard中创建的,那么这个子类重写 + ViewController 方法即可.
// FourViewController.m中
+ (instancetype)viewController {
return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"FourViewController"];
}
最后看下调用的地方.
- (IBAction)gotoSec:(id)sender {
UIViewController * vc = [UIViewController createViewController:@"SecondViewController" withParameter:@{}];
[vc setCallBack:^(NSDictionary * _Nonnull data) {
NSLog(@"可以设置回调");
}];
[self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)gotoThird:(id)sender {
UIViewController * vc = [UIViewController createViewController:@"ThirdViewController" withParameter:@{
@"type":@(3)
}];
[self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)gotoFour:(id)sender {
UIViewController * vc = [UIViewController createViewController:@"FourViewController" withParameter:@{@"projectId":@"846252845"}];
[self.navigationController pushViewController:vc animated:YES];
}
一样完成了组件化路由的东西 , 而且以后不往这个类跳转了 , 直接删除跳转的代码就行了 , 不需要找头文件删除了. 美滋滋
本文代码的 git地址 : https://github.com/guochaoshun/Router
看别人的router : https://www.jianshu.com/p/61f20e23afc0 , https://github.com/baoshanf/ALRouter
很多star的HHRouter例子 和 源码 : https://github.com/sch1111878/HHRouterExample , https://github.com/lightory/HHRouter