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进行记录操作,调用appDelegate单例设置一个属性记录当前视图控制器,然后对于需要进行present操作的视图控制器,继承于BaseViewController,那么每次present一个新的视图控制器,父视图控制器的viewWillAppear方法都会被执行:
-(void)viewWillAppear:(BOOL)animated{
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
delegate.presentingController = self;
} 在appDelegate.h文件里面添加一个属性presentingController,来记录当前视图控制器,注意这里的属性名并不是presentingViewController,不要搞混了。
然后,在需要处理事件的地方(如:点击事件),在点击事件的方法中加入如下代码,即可回到最初视图控制器显示页面:
- (void)clickButton:(id)sender {
AppDelegate *appDele = (AppDelegate *)[UIApplication sharedApplication].delegate;
if (appDele.presentingController){
UIViewController *vc = appDele.presentingController.presentingViewController;
if (vc.presentingViewController){
//循环获取present出来本视图控制器的视图控制器(简单一点理解就是上级视图控制器),一直到最底层,然后在dismiss,那么就ok了!
while (vc.presentingViewController){
vc = vc.presentingViewController;
}
[vc dismissViewControllerAnimated:YES completion:nil];
}
}
} 转自:http://blog.youkuaiyun.com/longshihua/article/details/51282388
本文介绍了一种在Swift中实现多级PresentViewController并能够一次性Dismiss所有层级返回初始ViewController的方法。通过创建BaseViewController并在其中记录当前最顶层的ViewController,利用递归查找的方式来Dismiss所有层级。
1万+

被折叠的 条评论
为什么被折叠?



