URL Router 可以將 UIViewController 映射成 URL,從而支持通過 URL 進(jìn)行界面跳轉(zhuǎn)霉祸,類似 Web 一樣筑累。URL Router 有著許多切實(shí)的好處。
一丝蹭、URL Router優(yōu)勢(shì)
1慢宗、減少 UIViewController 之間的耦合。在沒有 URL Router 的世界奔穿,如果 aViewController 需要跳轉(zhuǎn)到 bViewController镜沽,就必須依賴于后者,這很容易就造成錯(cuò)綜復(fù)雜的依賴鏈巫橄。引入 URL Router 后淘邻,這些鏈條自然就被斬?cái)唷?br> 需求場(chǎng)景:實(shí)現(xiàn)由controllerA跳轉(zhuǎn)到controllerB茵典,且為controllerB的各項(xiàng)屬性完成賦值操作(bVC的屬性變化較頻繁)湘换。
a. 在常規(guī)開發(fā)中,為了適應(yīng)controllerB不斷變化的屬性统阿,我們需要同時(shí)修改controllerA中的跳轉(zhuǎn)方法(因跳轉(zhuǎn)依賴后者彩倚,即controllerB)和controllerB的屬性聲明,controllerA和controllerB的耦合性較大扶平,在實(shí)現(xiàn)需求的過程中增價(jià)了開發(fā)的強(qiáng)度帆离。
b. 使用URL Router后,應(yīng)對(duì)controllerB不斷變化的屬性结澄,我們只需要修改controllerB即可哥谷,controllerB需要的各項(xiàng)參數(shù)可以通過URL Router的參數(shù)完成傳遞岸夯,大大降低了兩者的耦合性。
2们妥、使用URL Router后猜扮,每個(gè)界面都擁有唯一且不重復(fù)的 URL ,你將更容易實(shí)現(xiàn)這些以下需求:Push 打開指定的界面监婶、追蹤用戶瀏覽記錄旅赢、開放 URL Scheme等。
二惑惶、HHRouter使用詳解
1煮盼、這里使用cocoaPods演示使用過程,新建項(xiàng)目RouterDemo带污,編輯Podfile文件如下:
platform :ios, '7.0'
target 'RouterDemo' do
pod 'HHRouter', '~> 0.1.8'
end
執(zhí)行cocoa pods安裝命令僵控,安裝HHRouter。
2刮刑、在ViewController.m引入頭文件:
#import <HHRouter/HHRouter.h>
添加如下測(cè)試方法:
- (void)testMethod
{
[[HHRouter shared] map:@"/user/:userId/" toControllerClass:[UserViewController class]];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 100, 100, 40)];
[self.view addSubview:btn];
[btn setTitle:@"Skip" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(skip) forControlEvents:UIControlEventTouchUpInside];
}
- (void)skip
{
UIViewController *viewController = [[HHRouter shared] matchController:@"/user/10/"];
// XCTAssertEqualObjects([viewController class], [UserViewController class]);
// XCTAssertEqualObjects(viewController.params[@"route"], @"/user/1/");
// XCTAssertEqualObjects(viewController.params[@"userId"], @"1");
[self.navigationController pushViewController:viewController animated:YES];
}
即可利用“/user/10/”為鏈接跳轉(zhuǎn)到UserViewController喉祭,且傳遞參數(shù)userId=10。
3雷绢、在UserViewController中接收url傳過來的參數(shù)泛烙;
a. 在UserViewController.h中添加屬性
@property (nonatomic, strong) NSDictionary *params;
b. 在UserViewController.m添加實(shí)現(xiàn)
- (void)setParams:(NSDictionary *)params
{
_params = params; // 為私有屬性賦值
NSLog(@"Params: %@", params);
}
三、HHRouter原理分析
更多詳情請(qǐng)參照git文檔:https://github.com/Huohua/HHRouter
筆者根據(jù)HHRouter的原理翘紊,使用值傳遞蔽氨、面向協(xié)議的方式,基于swift4.0對(duì)其進(jìn)行了重寫帆疟,有興趣的同學(xué)可以參考:https://github.com/Andy-Swift/ASRouterDemo
如有不當(dāng)之處鹉究,歡迎各位同學(xué)討論指導(dǎo)。