多级Push页面后优雅的返回指定控制器几种方法

在开发过程中我们可能会遇到不同的产品需求,例如说A-->B--C,如果是层级返回的话我们只需要pop回去就好,但是如果是back到指定VC的时候,例如:A-->B--C,然后从C回到A,在开发过程中还是遇到的比较多的,本文总结了常见的三种方法,以此记录一下。

使用场景:  A -- > B -- > C,然后现在要求C直接pop回到A。

方法一

C返回到B的时候写个回调,B接收到回调再自己pop到A,但是这个方法B的页面会闪现一下,用户体验不好,不推荐。

方法一.gif

实现代码:
C_ViewController.h

#import 
typedef void (^backBlock)(void);     

@interface C_ViewController : UIViewController
@property (copy,nonatomic)backBlock backBlock;

@end

C_ViewController.m

-(void)back
{

    if (self.backBlock) {
        [self.navigationController popViewControllerAnimated:YES];
        self.backBlock();

    }
}

B_ViewController实现方法

C_ViewController *cViewController = [[C_ViewController alloc] init]; 
    [self.navigationController pushViewController:cViewController animated:YES];
    cViewController.backBlock = ^{
        [self.navigationController popViewControllerAnimated:YES];
    };

方法二

在B push 到C的时候,直接把B从导航控制器的堆栈中移除。

方法二.gif

实现方法:
B_ViewController实现方法

//  方法二
    NSMutableArray *arrM = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
    [arrM replaceObjectAtIndex:[arrM count]-1 withObject:cViewController];
    [self.navigationController setViewControllers:arrM animated:YES];

方法三

写一个UIViewController的catrgory,在C的backAct方法中使用

 

方法三.gif


实现方法:
UIViewController+BackToViewController.h

 

#import 

@interface UIViewController (BackToViewController)
-(void)backToController:(NSString *)controllerName animated:(BOOL )animaed;
@end

UIViewController+BackToViewController.m

@implementation UIViewController (BackToViewController)
-(void)backToController:(NSString *)controllerName animated:(BOOL)animaed{
    if (self.navigationController) {
        NSArray *controllers = self.navigationController.viewControllers;
        NSArray *result = [controllers filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
            return [evaluatedObject isKindOfClass:NSClassFromString(controllerName)];
        }]];
        if (result.count > 0) {
            [self.navigationController popToViewController:result[0] animated:YES];
        }
    }
}

在C_ViewController中使用

// 方法三
        if(self.navigationController.viewControllers.count <= 1)
        {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else
        {
            [self backToController:@"ViewController" animated:YES];
        }

这是我个人用的三种方法,比较推荐第三种方法,如有更好的方法麻烦告知,大家共同进步,谢谢。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值