Routable中的类
UPRouterOptions
UPRouter
Routable : UPRouter
RouterParams
Routable继承自UPRouter,提供了一个单例方法:+ (instancetype)sharedRouter;
保证一个生命周期中只使用同一个Routable
对象。
Routable是核心类,实现了注册、调用Open跳转页面等基本功能。
注册
[[Routable sharedRouter] map:@"user/:id" toController:[ViewController class]];
这里的map是和后台约定好的规则,user是host,后面接着你需要的参数,后台返回给你字符串,就可以自己去跳转和处理需要的参数了。注册的格式为host/:param1/:param2
查看源代码,他其实通过map值经过UPRouterOptions
类的转换,把map的值当做key映射到字典self.routes
里,value值是对应的viewcontroller
。
- (void)map:(NSString *)format toController:(Class)controllerClass withOptions:(UPRouterOptions *)options {
if (!format) {
@throw [NSException exceptionWithName:@"RouteNotProvided"
reason:@"Route #format is not initialized"
userInfo:nil];
return;
}
if (!options) {
// like [NSArray array]
options = [UPRouterOptions routerOptions];
}
options.openClass = controllerClass;
[self.routes setObject:options forKey:format];
}
页面跳转
注册成功后就可以调用open
方法进行页面跳转。
- (void)open:(NSString *)url animated:(BOOL)animated {
// routerParams 包含ViewController 打开的方式 参数(openParams)
RouterParams *params = [self routerParamsForUrl:url];
UPRouterOptions *options = params.routerOptions;
// callBack
if (options.callback) {
RouterOpenCallback callback = options.callback;
callback([params controllerParams]);
return;
}
if (!self.navigationController) {
if (_ignoresExceptions) {
return;
}
@throw [NSException exceptionWithName:@"NavigationControllerNotProvided"
reason:@"Router#navigationController has not been set to a UINavigationController instance"
userInfo:nil];
}
UIViewController *controller = [self controllerForRouterParams:params];
if (self.navigationController.presentedViewController) {
[self.navigationController dismissViewControllerAnimated:animated completion:nil];
}
if ([options isModal]) {
if ([controller.class isSubclassOfClass:UINavigationController.class]) {
[self.navigationController presentViewController:controller
animated:animated
completion:nil];
}
else {
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
navigationController.modalPresentationStyle = controller.modalPresentationStyle;
navigationController.modalTransitionStyle = controller.modalTransitionStyle;
[self.navigationController presentViewController:navigationController
animated:animated
completion:nil];
}
}
else if (options.shouldOpenAsRootViewController) {
[self.navigationController setViewControllers:@[controller] animated:animated];
}
else {
[self.navigationController pushViewController:controller animated:animated];
}
}
首先根据url
获取对应的RouterParams
对象,RouterParams包含RouterOptions
包含openClass
和跳转方式等,openParams
是需要传递的参数。
然后取到需要跳转的ViewController
,并且为参数赋值,设置跳转形式动画等。ViewController
需要实现initWithRouterParams:
方法或者allocWithRouterParams
方法,完成参数的传递。然后通过UPRouterOptions
中的参数判断跳转方式完成页面跳转。
如果是callBack
typedef void (^RouterOpenCallBack)(NSDictionary *params)