presentViewController是经常会用到的展现ViewController的方式,而显示和去除presentViewController也是很简单的,主要是下面两个方法:
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completionNS_AVAILABLE_IOS(5_0);
- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^__nullable)(void))completionNS_AVAILABLE_IOS(5_0);
但是有的时候我们的需求很特殊,比如在一个presentViewController里要present另一个viewController,甚至再present一个viewController,然后可能在某个时候APP发出一条消息,需要一下子dismiss掉所有的viewController,回到最开始的视图控制器,这时候该如何办呢?下面一起来看看解决办法?
首先,必须知道现在整个APP最顶层的ViewController是哪个,我的做法是建立一个父视图控制器,称为BaseViewController,然后在该视图控制器的viewWillAppear进行记录操作,使用视图控制器的presentingViewController属性记录当前视图控制器,然后对于需要进行present操作的视图控制器,继承于BaseViewController,那么每次present一个新的视图控制器,父视图控制器的viewWillAppear方法都会被执行:
-(void)viewWillAppear:(BOOL)animated{
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
delegate.presentingController = self;
}
最后,在需要处理时间的地方(如:点击事件),在点击事件的方法中加入如下代码,即可回到最初视图控制器显示页面:
- (void)clickButton:(id)sender {
AppDelegate *delegate=(AppDelegate *)[[UIApplicationsharedApplication]delegate];
if (delegate.presentingController)
{
UIViewController *vc =self.presentingViewController;
if ( !vc.presentingViewController ) return;
//循环获取present出来本视图控制器的视图控制器(简单一点理解就是上级视图控制器),一直到最底层,然后在dismiss,那么就ok了!
while (vc.presentingViewController)
{
vc = vc.presentingViewController;
}
[vc dismissViewControllerAnimated:YEScompletion:^{
}];
}
}
属性解析:
presentedViewController:The view controller that is presented by this view controlller(read-only),被本视图控制器present出来的的视图控制器(只读)
presentingViewController:The view controller that presented this view controller. (read-only),present出来本视图控制器的视图控制器(只读)