文/XinStar(简书作者)
原文链接:http://www.jianshu.com/p/0e25361653a5
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
http://stackoverflow.com/questions/1214965/setting-action-for-back-button-in-navigation-controller/19132881#19132881
就是那个获得120个赞同的答主,他写了一个extension,你只要把那两个文件拖到你项目里,然后重写一个方法就好了
- (BOOL)navigationShouldPopOnBackButton {
if (要弹出提示) {
// 在这里创建UIAlertController等方法
return NO;
}
return YES;
}
如何自定义系统自带返回按钮?
在另一篇文章中写过,由A push到B, 那么B 的返回按钮,需要在A中的 push to B 动作之前设置,即写下面一段即可 把B的返回按钮由 “< A”, 改成“< Back”
#pragma mark - custom timeBoxVC's back BarButtonItem to be "Back", this setting must be added before "push" action;
UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
backItem.title = @"Back";
self.navigationItem.backBarButtonItem = backItem;
#pragma mark
[self.navigationController pushViewController:B animated:YES];
如何创建UIViewcontrolller category 类 并实现改变iOS系统自带返回按钮事件?
1/. 在xCode中,command + n 选择 OS X 创建object - C file - category file, 创建一个UIViewController的扩展类, 或直接拖拽上面stackOverflow答主写的两个文件到工程中
"UIViewController+SystemBackButtonHandler.h"
"UIViewController+SystemBackButtonHandler.m"
2/. 在需要改变 或自定义系统自带返回按钮的那个Viewcontroller中,import "UIViewController+SystemBackButtonHandler.h" 文件,并 重写UIViewController的扩展类里的代理方法 -(BOOL)navigationShouldPopOnBackButton, 在这个方法中 返回YES, 指出现跳转动作 返回NO, 指不执行跳转, 可以自定义在执行跳转前 出现AlertView, 或popToRootVC, 或popTo指定的VC, 这些都是系统自带的返回按钮pop事件所不能做到的,系统自带的返回按钮默认只能返回上一页,不能出现AlertView, 或popToRootVC, 或popTo指定的VC。。。
///.h内容
#import <UIKit/UIKit.h>
@protocol BackButtonHandlerProtocol <NSObject>
@optional
// Override this method in UIViewController derived class to handle 'Back' button click
-(BOOL)navigationShouldPopOnBackButton;
@end
@interface UIViewController (SystemBackButtonHandler)<BackButtonHandlerProtocol>
@end
///.m内容
@implementation UIViewController (SystemBackButtonHandler)
@end
@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.;
}];
}
}
}