统一返回按钮
自定义UINavigationController子类:JQNavigationController
拦截- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
方法,在push之前统一修改目标控制器的leftBarButtonItem
JQNavigationController.m
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
//如果先调用[super pushViewController:viewController animated:animated];
//会在主界面就隐藏tabBar
if (self.viewControllers.count > 0 ) {
//跳转到之后的控制器隐藏tabBar
viewController.hidesBottomBarWhenPushed = YES;
//统一设置返回按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"navigationButtonReturn"] forState:UIControlStateNormal];
[button setTitle:@"返回" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setContentEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
[button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
viewController.navigationItem.leftBarButtonItem = item;
}
//跳转控制器
[super pushViewController:viewController animated:animated];
}
- (void)back {
[self popViewControllerAnimated:YES];
}
全屏返回手势
用上述这种方法修改返回按钮会使系统的滑动返回手势失效,因此我们要自己管理手势比较有效的方法是添加自定义的Pan手势
JQNavigationController.m
- (void)viewDidLoad {
[super viewDidLoad];
// target= <(action=handleNavigationTransition:, target=<_UINavigationInteractiveTransition 0x7fd94f60a060>)>>
//使系统的滑动返回手势不可用
self.interactivePopGestureRecognizer.enabled = NO;
//添加全屏滑动返回手势
[self addPanGesture];
}
- (void)addPanGesture {
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.interactivePopGestureRecognizer.delegate action:@selector(handleNavigationTransition:)];
[self.view addGestureRecognizer:panGesture];
panGesture.delegate = self;
}
注意:
self.interactivePopGestureRecognizer.delegate
是系统原先处理返回手势的代理
handleNavigationTransition:
是系统原先处理返回手势的实现,在这里利用系统的实现就不用自行实现手势返回
这样添加手势之后会有小bug,就是在导航控制器的根视图控制器滑动返回时,会造成假死,解决方法:不处理在视图控制器的滑动手势返回
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
//不让导航控制器在根视图控制器滑动返回
return self.childViewControllers.count > 1;
}
#pragma mark - end
以上
自定义这样的一个类就可以实现开发常用的统一返回按钮与全屏滑动返回