![](https://i-blog.csdnimg.cn/blog_migrate/a13ccc4a753e3a4a6f94c22e8e89e0bf.png)
//HomeVC.m
#import "HomeVC.h"
#import <MGJRouter/MGJRouter.h>
@interface HomeVC ()
@end
@implementation HomeVC
- (IBAction)mg_cAction:(id)sender {
[MGJRouter openURL:@"NIU://home/pageMine” withUserInfo:@{@"VC" : self} completion:nil];
[MGJRouter openURL:@"NIU://home/pageMine/666" withUserInfo:@{@"VC" : self} completion:nil];
// 获取对象
UIView *searchTopBar = [MGJRouter objectForURL:@"NIU://search_top_bar"];
[self.view addSubview:searchTopBar];
//block点击回调
[MGJRouter openURL:@"NIU://home/pageMine" withUserInfo:@{@"VC" : self,@"block":^(NSString * text){
NSLog(@"%@",text);
}}completion:nil];
}
@end
/*
MGJRouter
1.路由中心维护着一张路由表,URL为key, block为value。
2.注册路由表时,将key和value对应保存到路由表routes中
3.使用时,根据URL拿到对应的block进行执行。
*/
+ (instancetype)sharedInstance
{
static MGJRouter *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
- (NSMutableDictionary *)routes
{
if (!_routes) {
_routes = [[NSMutableDictionary alloc] init];
}
return _routes;
}
//URL对UIImage,NSData这样的对象是很难传递的
MineVC.m
#import "MineVC.h"
#import <MGJRouter/MGJRouter.h>
typedef void(^btnClickBlock)(NSString *);
@interface MineVC ()
@property (nonatomic, copy)btnClickBlock clicked;
@end
@implementation MineVC
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (self.clicked){
self.clicked(@"Mine页面点击回调的");
}
[self dismissViewControllerAnimated:YES completion:nil];
}
// 在load方法中自动注册
+ (void)load {
[MGJRouter registerURLPattern:@"NIU://home/pageMine" toHandler:^(NSDictionary *routerParameters) {
NSLog(@"Mine页面接受参数 - %@",routerParameters);
UIViewController *curVC = routerParameters[MGJRouterParameterUserInfo][@"VC"];
MineVC *vc = [[MineVC alloc] init];
[curVC presentViewController:vc animated:YES completion:nil];
}];
[MGJRouter registerURLPattern:@"NIU://home/pageMine/:id" toHandler:^(NSDictionary *routerParameters) {
NSLog(@"Mine页面接受参数 - %@",routerParameters);
UIViewController *curVC = routerParameters[MGJRouterParameterUserInfo][@"VC"];
MineVC *vc = [[MineVC alloc] init];
[curVC presentViewController:vc animated:YES completion:nil];
}];
[MGJRouter registerURLPattern:@"NIU://search_top_bar" toObjectHandler:^id(NSDictionary *routerParameters) {
UIView *searchTopBar = [[UIView alloc] init];
searchTopBar.frame = CGRectMake(0, 299, 100, 100);
searchTopBar.backgroundColor= UIColor.greenColor;
return searchTopBar;
}];// 返回一个 view 对象
[MGJRouter registerURLPattern:@"NIU://home/pageMine" toHandler:^(NSDictionary *routerParameters) {
UIViewController *curVC = routerParameters[MGJRouterParameterUserInfo][@"VC"];
void(^block)(NSString *) = routerParameters[MGJRouterParameterUserInfo][@"block"];
MineVC *vc = [[MineVC alloc] init];
vc.clicked = block;
[curVC presentViewController:vc animated:YES completion:nil];
}];// block 回调
}
@end