iOS控制器有两种跳转方式:
1.模态跳转
2.导航控制器跳转
1.模态跳转
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion
- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion
dismissViewControllerAnimated:
模态跳转返回
如果有多个模态控制器,用下面的VC调用此方法,会一次性释放该VC及以上VC 但是只有最上层的VC可以有动画
如果VC模态出的控制器VC1中有navigationController,无论nav push多少控制器 通过VC调用改方法,所有nav栈中vcs被释放,并且VC dismiss,即所有模态出来的之后的控制器全部被释放.
通过VC1.presentingViewController获取VC,presentingViewController只能获取上一层的VC,如需多层,需要循环获取
UIViewController *vc = self.presentingViewController;
while (vc.presentingViewController) {
vc = vc.presentingViewController;
}
2.导航控制器跳转
常用跳转方式:
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (nullable UIViewController *)popViewControllerAnimated:(BOOL)animated;
- (nullable NSArray<__kindof UIViewController *> *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (nullable NSArray<__kindof UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated;
- (void)setViewControllers:(NSArray<UIViewController *> *)viewControllers animated:(BOOL)animated NS_AVAILABLE_IOS(3_0);
这些跳转方式可以满足大部分的跳转方式,如果项目复杂一些,可能会有一些特别的需求,例如:跳转前判断是否登录,登录直接跳转,未登录需要登录之后在跳转;或者tabBarController index=0的控制器进入push很多次之后需要跳转到index=1的控制器的下一级控制器
BFTabBarController *tb = [UIApplication sharedApplication].keyWindow.rootViewController;
tb.selectedIndex = 1;
[self.navigationController popToRootViewControllerAnimated:YES];
TestViewController *vtestc = [[TestViewController alloc] init];
vtestc.str = @"1";
BaseNavigationViewController *vc = tb.selectedViewController;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[vc pushViewController:vtestc animated:YES];
});
popToRootViewControllerAnimated 写在tb.selectedIndex下面,可以有动画
然后pushViewController需要在dispatch_after中
原因:动画需要时间,视图加载需要时间
可能遇到的问题:1.先pop再tb.selectedIndex那么selectedIndex没有tabbar
2.如果从selectedIndex=0的控制器返回再push selectedIndex=1(>0)的控制器的下级控制器,这时候selectedIndex=1的控制器还没加载,导致无法push,如果此前加载过可以push,解决方法是使用dispatch_after
网友评论