在实际项目中,经常需要自定义导航栏实现手势返回,当然还有很多其他的功能,自行参考就好,废话不多说,直接上代码
创建一对继承于UINavigationController 的文件
.m 中这么写
#import "BaseNVC.h"
@interface BaseNVC ()<UIGestureRecognizerDelegate>
@property(nullable, nonatomic, readonly) UIGestureRecognizer *interactivePopGesture;
@end
@implementation BaseNVC
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.interactivePopGesture.enabled = NO;
// self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
// 统一设置 bar 的字体大小和颜色
+(void)initialize{
UINavigationBar *navTheme = [UINavigationBar appearance];
[navTheme setTitleTextAttributes:@{NSFontAttributeName:FONT_RATIO(17.f), NSForegroundColorAttributeName:[UIColor whiteColor]}];
[navTheme setBarTintColor:NAVIGATION_COLOR];
[navTheme setTintColor:NAVIGATION_COLOR];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
__weak id weakSelf = self;
self.interactivePopGestureRecognizer.delegate = weakSelf;
}
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
self.interactivePopGestureRecognizer.delegate = nil;
}
/**
* 能拦截所有push进来的子控制器
*/
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
if (self.viewControllers.count > 0) { // 如果现在push的不是栈底控制器(最先push进来的那个控制器)
viewController.hidesBottomBarWhenPushed = YES;
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Nav_back_ic"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
}
[super pushViewController:viewController animated:YES];
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
BOOL isBack = YES; // 默认为支持右滑反回
if ([self.topViewController isKindOfClass:[BaseNVC class]]) {
if ([self.topViewController respondsToSelector:@selector(gestureRecognizerShouldBegin)]) {
BaseNVC *vc = (BaseNVC *)self.topViewController;
isBack = [vc gestureRecognizerShouldBegin:self.interactivePopGesture];
}
}
return isBack;
}
- (void)back
{
[self popViewControllerAnimated:YES];
}
- (UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
- (void)gestureRecognizerShouldBegin{
[self popViewControllerAnimated:YES];
}
#pragma mark ---- 加入这行代码 (防止手势返回再进入卡顿现象)---
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return self.childViewControllers.count > 1;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
希望对你有帮助!!!