需求:
新开一个Controller显示界面,但是可以在不销毁Controller的前提下隐藏,显示上一个界面,并且可以来回随意切换
原理:
通过transitionFromViewController这个方法,将当前视图和新的视图加到新设置的根控制器上作为子视图
@property(nonatomic ,assign) BOOL showNewVc;
@property(nonatomic ,assign) BOOL isTouch;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (_isTouch) {
return;
}
// 设置新的rootviewController
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
// 获取根控制器
UIViewController *rootVc = appdelegate.window.rootViewController;
// 设置新的根控制器
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
简易效果图:
q0gej-mehfl.gif
网友评论