如何实现退出页面但是不销毁页面

2024-07-19  本文已影响0人  江湖闹士

项目中可能会遇到类似场景,比如:从二级页面返回上一级页面,但是二级页面还是存在的,如果再次进入二级页面,还是保留之前的状态,也就是二级页面不被销毁。等真正的关闭二级页面的时候才销毁该页面。
实现原理是,上一级页面强制引用一下二级页面的导航控制器,只要这个导航控制不被销毁,那么二级页面就不会被销毁。想要二级页面销毁的话,只需要将上级页面引用的导航控制器置为nil即可,注:跳转使用modal,不用push

AViewController为一级页面,BViewController为二级页面
1、从A跳转到B,然后从B退出到A时保留B
2、在保留B的情况下,再次进入B还是之前的页面状态
3、在B中进行关闭操作,直接销毁自己,退出
4、在保留B的情况下,在A中直接销毁B

代码如下:

#import "AViewController.h"
@interface AViewController ()
//强制引用nav
@property (nonatomic,strong) UINavigationController *nav;
@end

@implementation AViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //定义UI,需要两个按钮,来实现下面的两个点击方法,一个是跳转BViewController页面的方法,一个是关闭BViewController的方法
    //添加按钮代码。。。。。


    //接收二级页面内部点击关闭页面的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchNoti:) name:@"closeBController" object:nil];
    
}

//接收通知
- (void)fetchNoti:(NSNotification *)noti{
    //二级页面内部点击关闭页面,则要通知到外部一级页面,进行将导航控制器置为nil,二级页面才会被销毁
    if (self.nav) {
        self.nav = nil;
    }
}

//跳转到BViewController方法
- (void)jumpToBViewController{
    if (self.nav) {
        //如果导航控制器存在,说明之前跳转过,二级页面还没有销毁,直接跳转即可
        [self presentViewController:self.nav animated:YES completion:^{
            NSLog(@"已经跳转");
        }];
        return;
    }

    //如果导航控制器不存在,说明首次跳转或者二级页面已经被销毁,则重新初始化后跳转
    SJTestViewController *vc = [[SJTestViewController alloc] init];
    self.nav = [[UINavigationController alloc] initWithRootViewController:vc];
    self.nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:self.nav animated:YES completion:^{
        NSLog(@"已经跳转");
    }];
    
}

//如果从二级页面返回后没有被销毁,想在一级页面有个按钮销毁二级页面
- (void)onAPageCloseBViewController{
    if(self.nav){
        self.nav = nil;
    }
}
@implementation BViewController ()

- (void)viewDidLoad {

    //  UI代码编写,两个按钮,一个退出操作(页面不销毁),一个关闭操作(页面销毁)
}

//退出操作(页面不销毁)
- (void)quitAction:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//关闭操作(页面销毁,原理就是给外部通知了)
- (void)closeAction:(UIButton *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"closeBController" object:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//用来测试页面是否被释放了
- (void)dealloc{
    NSLog(@"彻底释放");
}
@end
上一篇 下一篇

猜你喜欢

热点阅读