- 应用场景需求:在app中,一般给导航控制器push的子控制器的返回按钮统一设置,而不是用系统的默认返回按钮
- 分析:
- 1 自定义返回按钮(UIButton)
- 2 自定义返回按钮后,系统不会给自定义的按钮添加返回功能,需要手动添加方法,实现返回功能
- 3 自定义返回按钮后,系统也不会给自定义的按钮添加侧滑功能,原因是侧滑手势识别器代理方法系统取消了
- 解决方案:
- 1 设置手势交互识别器的代理
- 2 遵守代理协议
- 3 实现代理方法
- 4 重写push方法的目的 : 拦截所有push进来的子控制器在里面自定义全局的返回按钮
#import "OSNaViewController.h"
@interface
OSNaViewController
() <UIGestureRecognizerDelegate>
@end@implementation OSNaViewController
- (void)viewDidLoad { [super viewDidLoad]; self.interactivePopGestureRecognizer.delegate = self; [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackgroundWhite"] forBarMetrics:UIBarMetricsDefault];}
1. 重写push方法的目的 : 拦截所有push进来的子控制器
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (self.childViewControllers.count > 0) {
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:[UIImage imageNamed:@"图片名称"] forState:UIControlStateNormal];
[backButton setImage:[UIImage imageNamed:@"图片名称"] forState:UIControlStateHighlighted];
[backButton setTitle:@"返回" forState:UIControlStateNormal];
[backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[backButton setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[backButton sizeToFit];
backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
[backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
viewController.hidesBottomBarWhenPushed = YES;
}
[super pushViewController:viewController animated:animated];
}
2. 监听返回按钮的点击
- (void)back
{
[self popViewControllerAnimated:YES];
}
3. 手势识别器对象会调用这个代理方法来决定手势是否有效
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return self.childViewControllers.count > 1;
}