iOS 防止页面重复Push
前言
项目中是否有遇到一个页面被重复Push两次的情况呢?这种情况是存在的,比如很短的时间内联系点击两次按钮,导致页面跳转两次的情况。应该怎么避免呢?
解决方案
解决这个问题的方案有很多种,这里提供一种全局的解决方案。通过复写NavigationController的pushViewController:animate: 来解决。
在初始化的NavigationController中复写以下方法,
// Overwrite the function and preventing repeated push.
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
if ([self.viewControllers.lastObject isKindOfClass:[viewController class]]) {
return;
}
[super pushViewController:viewController animated:animated];
}
测试
在HomeViewController中点击按钮直接调用两次push,模拟多次跳转的情况。
#import "HomeViewController.h"
#import "MoreViewController.h"
@interface HomeViewController ()
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"Home";
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
button.frame = CGRectMake(CGRectGetMidX(self.view.frame)-30, CGRectGetMidY(self.view.frame)-30, 60, 60);
[self.view addSubview:button];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonAction:(UIButton *)sender
{
MoreViewController *moreViewController1 = [[MoreViewController alloc] init];
MoreViewController *moreViewController2 = [[MoreViewController alloc] init];
[self.navigationController pushViewController:moreViewController1 animated:YES];
[self.navigationController pushViewController:moreViewController2 animated:YES];
}
@end
在NavigationController中断点,查看第二次push会不会被拦截。
#import "MMNavigationController.h"
@interface MMNavigationController ()
@end
@implementation MMNavigationController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
// Overwrite the function and preventing repeated push.
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
if ([self.viewControllers.lastObject isKindOfClass:[viewController class]]) {
return;
}
self.modalPresentationStyle = UIModalPresentationFullScreen;
[super pushViewController:viewController animated:animated];
}
@end
通过测试,第二次push会被return掉,以此来防止重复push的情况。