iOS 隱藏控制器 UIViewController

需求:
新開一個(gè)Controller顯示界面,但是可以在不銷毀Controller的前提下隱藏,顯示上一個(gè)界面,并且可以來回隨意切換

原理:
通過transitionFromViewController這個(gè)方法,將當(dāng)前視圖和新的視圖加到新設(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

簡易效果圖:

q0gej-mehfl.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容