在开发过程中我们可能会遇到不同的产品需求,例如说A–>B–C,如果是层级返回的话我们只需要pop回去就好,但是如果是back到指定VC的时候,例如:A–>B–C,然后从C回到A,在开发过程中还是遇到的比较多的,本文总结了常见的三种方法,以此记录一下。
使用场景: A – > B – > C,然后现在要求C直接pop回到A。
方法一
C返回到B的时候写个回调,B接收到回调再自己pop到A,但是这个方法B的页面会闪现一下,用户体验不好,不推荐。
实现代码:C_ViewController.h
1
2
3
4
5
6
7#import <UIKit/UIKit.h>
typedef void (^backBlock)(void);
@interface C_ViewController : UIViewController
@property (copy,nonatomic)backBlock backBlock;
@end
C_ViewController.m
1
2
3
4
5
6
7
8
9-(void)back
{
if (self.backBlock) {
[self.navigationController popViewControllerAnimated:YES];
self.backBlock();
}
}
B_ViewController实现方法
1
2
3
4
5C_ViewController *cViewController = [[C_ViewController alloc] init];
[self.navigationController pushViewController:cViewController animated:YES];
cViewController.backBlock = ^{
[self.navigationController popViewControllerAnimated:YES];
};
方法二
在B push 到C的时候,直接把B从导航控制器的堆栈中移除。
实现方法:B_ViewController实现方法
1
2
3
4// 方法二
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方法中使用
实现方法:UIViewController+BackToViewController.h
1
2
3
4
5#import <UIKit/UIKit.h>
@interface UIViewController (BackToViewController)
-(void)backToController:(NSString *)controllerName animated:(BOOL )animaed;
@end
UIViewController+BackToViewController.m
1
2
3
4
5
6
7
8
9
10
11
12@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中使用
1 | // 方法三 |
这是我个人用的三种方法,比较推荐第三种方法,如有更好的方法麻烦告知,大家共同进步,谢谢。