遇到一个小问题,当用户点的不是保存而是系统自带的返回,我就弹出一个提示框问是否保存后再返回。相信大家开发过程中也经常会遇到这样的需求,刚开始我是想着自定义一个返回按钮,可是还想做成系统的,因为我大部分的返回按钮都是用的系统的,但是发现挺麻烦,效果也不一定好,于是各种查,目测有大神实现过了,果不其然,请看链接
https://github.com/onegray/UIViewController-BackButtonHandler
该大神做了一个UIViewController的extension,其实里面代码实现很简单
@implementation UINavigationController (ShouldPopOnBackButton)
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
if([self.viewControllers count] < [navigationBar.items count]) {
return YES;
}
BOOL shouldPop = YES;
UIViewController* vc = [self topViewController];
if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
shouldPop = [vc navigationShouldPopOnBackButton];
}
if(shouldPop) {
dispatch_async(dispatch_get_main_queue(), ^{
[self popViewControllerAnimated:YES];
});
} else {
// Workaround for iOS7.1. Thanks to @boliva - http://stackoverflow.com/posts/comments/34452906
for(UIView *subview in [navigationBar subviews]) {
if(0. < subview.alpha && subview.alpha < 1.) {
[UIView animateWithDuration:.25 animations:^{
subview.alpha = 1.;
}];
}
}
}
return NO;
}
@end
你只要把那两个文件引入到你项目里,然后重写一个方法就好了
- (BOOL)navigationShouldPopOnBackButton {
if (要弹出提示) {
// 在这里创建UIAlertController等方法
return NO;
}
return YES;
}
其实也可以这样去操作同一个页面根据判断条件跳转到不同页面,可以试试~