需求:
新開一個Controller顯示界面,但是可以在不銷毀Controller的前提下隱藏,顯示上一個界面路捧,并且可以來回隨意切換
原理:
通過transitionFromViewController這個方法箩退,將當前視圖和新的視圖加到新設(shè)置的根控制器上作為子視圖
@property(nonatomic ,assign) BOOL showNewVc;
@property(nonatomic ,assign) BOOL isTouch;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (_isTouch) {
return;
}
// 設(shè)置新的rootviewController
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
// 獲取根控制器
UIViewController *rootVc = appdelegate.window.rootViewController;
// 設(shè)置新的根控制器
UIViewController *tmpController = [[UIViewController alloc] init];
appdelegate.window.rootViewController = tmpController;
// 新的視圖
NewViewController *newVc = [[NewViewController alloc] init];
[tmpController addChildViewController:rootVc];
[tmpController addChildViewController:newVc];
[tmpController.view addSubview:rootVc.view];
// 顯示新的視圖
[tmpController transitionFromViewController:rootVc toViewController:newVc duration:0.1 options:UIViewAnimationOptionTransitionNone animations:^{
} completion:^(BOOL finished){
self.showNewVc = YES;
self.isTouch = YES;
}];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 100, 150, 100)];
btn.backgroundColor = [UIColor blueColor];
[btn setTitle:@"切換視圖" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(touchWay) forControlEvents:UIControlEventTouchUpInside];
[appdelegate.window addSubview:btn];
}
- (void) touchWay {
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
UIViewController *rootVc = appdelegate.window.rootViewController;
UIViewController *firstVc = [rootVc.childViewControllers firstObject];
UIViewController *secondVc = [rootVc.childViewControllers lastObject];
if (_showNewVc) {
[rootVc transitionFromViewController:secondVc toViewController:firstVc duration:0.1 options:UIViewAnimationOptionTransitionNone animations:nil completion:nil];
_showNewVc = NO;
} else {
[rootVc transitionFromViewController:firstVc toViewController:secondVc duration:0.1 options:UIViewAnimationOptionTransitionNone animations:nil completion:nil];
_showNewVc = YES;
}
}
demo地址: https://github.com/chengzj456/HideViewController
簡易效果圖: