APP中經(jīng)常有根據(jù)標(biāo)簽來切換頁面的需求恭金,如果切換的頁面只是刷新一下數(shù)據(jù)也就罷了双泪,但是如果每個(gè)標(biāo)簽切換頁面的數(shù)據(jù)和內(nèi)容、結(jié)構(gòu)完全不同你會(huì)怎么樣做?(例如:圖1-1)
圖1-1
個(gè)人覺得理想的做法就是每個(gè)標(biāo)簽展示的內(nèi)容為一個(gè)View,這樣切換既不會(huì)影響之前View還可以快速切回之前的View,而且符合高聚合、低耦合開發(fā)啊鸟整,這里就要隆重介紹一下addChildViewController
方法:
//在ViewController 中添加其他UIViewController,currentVC是一個(gè)UIViewController變量朦蕴,存儲(chǔ)當(dāng)前顯示的viewcontroller
FirstVC * first = [[FirstVC alloc] init];
[self addChildViewController:first];
//addChildViewController 會(huì)調(diào)用 [child willMoveToParentViewController:self] 方法篮条,但是不會(huì)調(diào)用 didMoveToParentViewController:方法,官方建議顯示調(diào)用
[first didMoveToParentViewController:self];
[first.view setFrame:CGRectMake(0, CGRectGetMaxY(myScrollView.frame), width, height-CGRectGetHeight(myScrollView.frame))];
currentVC = first;
[self.view addSubview:currentVC.view];
//這里沒有其他addSubview:方法了吩抓,就只有一個(gè)涉茧,而且可以切換視圖,是不是很神奇疹娶?
second = [[SecondVC alloc] init];
[second.view setFrame:CGRectMake(0,CGRectGetMaxY(myScrollView.frame), width, height-CGRectGetHeight(myScrollView.frame))];
蘋果已經(jīng)給我寫好切換UIViewController的transitionFromViewController
方法了:
#pragma mark - 切換viewController
- (void)changeControllerFromOldController:(UIViewController *)oldController toNewController:(UIViewController *)newController
{
[self addChildViewController:newController];
/**
* 切換ViewController
*/
[self transitionFromViewController:oldController toViewController:newController duration:0.3 options:UIViewAnimationOptionCurveEaseIn animations:^{
//做一些動(dòng)畫
} completion:^(BOOL finished) {
if (finished) {
//移除oldController伴栓,但在removeFromParentViewController:方法前不會(huì)調(diào)用willMoveToParentViewController:nil 方法,所以需要顯示調(diào)用
[newController didMoveToParentViewController:self];
[oldController willMoveToParentViewController:nil];
[oldController removeFromParentViewController];
currentVC = newController;
}else
{
currentVC = oldController;
}
}];
}
效果如下:
圖1-2 精選頁面
圖1-3 切換到發(fā)現(xiàn)頁面
寫到這里大家對addChildViewController
有一定的了解了雨饺,當(dāng)一個(gè)界面比較復(fù)雜的時(shí)候我們就可以采用這種方式來降低耦合度(如果各位有更加好的方法钳垮,希望不要吝惜交流一下),這樣做對頁面的邏輯更加分明额港,如果有可以重用的也方便重用饺窿,而且View沒有顯示也不會(huì)load,減少內(nèi)存的使用移斩。
同時(shí)肚医,還可以在一個(gè)parent ViewController上添加多個(gè)child ViewController,實(shí)際中這樣的頁面也是挺多的向瓷,如圖1-4
//在ViewController 中添加其他UIViewController
FirstVC * first = [[FirstVC alloc] init];
[self addChildViewController:first];
//addChildViewController 會(huì)調(diào)用 [child willMoveToParentViewController:self] 方法肠套,但是不會(huì)調(diào)用 didMoveToParentViewController:方法,官方建議顯示調(diào)用
[first didMoveToParentViewController:self];
[first.view setFrame:CGRectMake(0, CGRectGetMaxY(myScrollView.frame), width, 300)];
[self.view addSubview:first.view];
SecondVC * second = [[SecondVC alloc] init];
[self addChildViewController:second];
[second didMoveToParentViewController:self];
[second.view setFrame:CGRectMake(0,CGRectGetMaxY(first.view.frame), width, 300)];
[self.view addSubview:second.view];
圖1-4