iOS:关于A页面跳转到B页面,B页面跳转到C页面,点击C页面直接返回到A页的几种方法

相信在做项目的时候,各位同学都有碰到,这样一个问题,页面二级跳转或三级跳转,一键返回到一级页面的需求
今天有个小伙伴问我,他的需求是,在提交一个表单的页面,提交成功后,要展示一个提交表单成功的页面,当用户此时点击返回按钮事,页面就要略过表单页面,放回到上一级页面。
也就是A 跳转到 B(表单页面) ,表单提交成功跳转到 C(提交成功页面),在C页面点击返回按钮,直接返回到A页面。
下面来介绍第一种方法
============
我的第一想法是这样的,点C的时候直接返回A,那就在C页面定义个Block,当点击返回,调用Block事件,在BLock里面写返回事件,
C.h

#import "BaseViewController.h"
// 定义Block
typedef void(^BackBlock)(void);

/**
 *  创建团队
 */
@interface CreatTeam : BaseViewController

// 创建一个Block的实例
@property (nonatomic, copy) BackBlock backBlock;

@end

C.m

// 返回事件
- (void)back {
    [self.navigationController popViewControllerAnimated:NO];
  // 防止循环引用
    __weak typeof(self) weakSelf = self;
    weakSelf.backBlock();

    [SVProgressHUD dismiss];
}

然后在B控制器的
B.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            CreatTeam *creatVC = [[CreatTeam alloc] init];
            creatVC.team = _teams[indexPath.row];
            creatVC.backBlock = ^(){
                [self.navigationController popViewControllerAnimated:NO];
                
            };
            [self.navigationController pushViewController:creatFromCompanyVC animated:YES];
        }
}

这种方法,使用起来显得有点繁琐,并且一定要将动画关掉,否则会穿帮。不过这也算是一条思路。

下面来介绍第二种方法

第二种方法的思路是这样的,是可以获取到所有的控制器的数组,当页面跳转到C页面的时候,就将B页面从数据中移除掉,这样点击返回按钮的时候,页面直接就跳转到了A页面。
上代码:
在C.m

- (void)back {
    // 获取所有的控制器数组
    NSMutableArray *vcArr = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    // 将上级页面从数组中移除
    [vcArr removeObjectAtIndex:vcArr.count-2];
    self.navigationController.viewControllers = vcArr;
  
    [self.navigationController popViewControllerAnimated:NO];
    [SVProgressHUD dismiss];
}

下面来介绍第三种方法

第三种方法的思路是这样的,不对控制器数组中的元素做改变,而是直接在控制器数组中找到想要跳转的那个控制器所在的位置,获取到该控制器,然后进行pop。

NSInteger num = self.navigationController.viewControllers.count;
if (num > 3) {
   UIViewController *popVC =    self.navigationController.viewControllers[num - 3];
   [self.navigationController popToViewController:popVC animated:YES];
    }

啊哈,就是这么简单,完成跳转
第三种方法是随意跳转的哦



作者:斯文_7
链接:https://www.jianshu.com/p/c4d1eb226eaf
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2022-10-28 10:56  brave-sailor  阅读(332)  评论(0编辑  收藏  举报