iOS页面跳转遇到Whose view is not in the window hierarchy问题

因为手上项目用的是纯代码来写,我一个小白直接上手感觉特别吃力。纯代码写页面跳转一般用的是模态视图的方法,而我之前接触到的一般都是用导航控制器UINavigationController进行跳转,而且指导的大佬要求页面逻辑和页面布局要分开,这样一绕我就更头晕了。

简单梳理一下先:

UINavigationController跳转:

UINavigationController的原理就是相当于一个装载视图(viewController)的容器(栈),它可以放很多视图,当然视图的进出也和数据结构里面栈的进出类似。

1. 由当前显示的界面压入新的视图:

[self.navigationController pushViewController:viewController animated:NO]

2.弹出视图的方法有三个变型:

① 弹出当前的页面,返回上一个页面(如果是根视图则不会弹出)

[self.navigationController popViewControllerAnimated:YES]

② 直接弹出到根视图

[self.navigationController popToRootViewControllerAnimated:YES]; 

③ 弹出到指定视图(需要做一个遍历判断)

UIViewController *viewController=nil;
for (UIViewController *popVc in self.navigationController.viewControllers) {

    if ([popVc isKindOfClass:[UIViewController class]]) {
        viewController=popVc;
        }
    }
[self.navigationController popToViewController:viewController animated:YES];

模态视图:

模态视图常用的切换方法有两种:

① 弹出现一个新视图,可以带动画效果,完成后可以做相应的执行函数经常为nil

[presentingViewContoller presentViewController:presentedViewContoller animated:YES completion:nil]

② 退出得到一个新视图,后面那个参数和present方法一致

[presentingViewContoller dismissViewControllerAnimated:YES completion:nil]

说到这里就需要理解视图控制器的两个重要的属性,presentedViewController和presentingViewController,其实这二者一般情况下是父子关系,当然你也可以用栈的思维去理解它——presenting到栈底就是root视图,而presented到栈顶就是当前视图。

所以如果利用模态转换要做到popToRootViewController同样效果的操作,你就需要一直presenting:

UIViewController *vc = self.presentingViewController;
while (vc.presentingViewController) {

    vc = vc.presentingViewController;
}
[vc dismissViewControllerAnimated:YES completion:nil];

解决问题:

我的B在从A中present过后,没办法定位其位置,从而无法从B再present到C时,报错:Whose view is not in the window hierarchy。所以我们现在的办法就是去找到B的位置,即当前我们现实的视图。

UIViewController *topViewContoller = self.presentingViewController;
while (topViewContoller .presentingViewController) {

    topViewContoller = topViewContoller .presentingViewController;
}
[topViewContoller presentViewController:viewContollerToPresent animated:YES completion:nil];

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值