继承系统提供的UINavigationViewController,拦截并重写其push方法。
#import "DJNavigationController.h" @implementation DJNavigationController - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated { if (self.viewControllers.count > 0) { // 自定义左上角按钮 UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [backBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_back"] forState:UIControlStateNormal]; [backBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_back_highlighted"] forState:UIControlStateHighlighted]; backBtn.size = backBtn.currentBackgroundImage.size; [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn]; viewController.navigationItem.leftBarButtonItem = leftItem; // 自定义右上角按钮 UIButton *homeBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [homeBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_more"] forState:UIControlStateNormal]; [homeBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_more_highlighted"] forState:UIControlStateHighlighted]; homeBtn.size = homeBtn.currentBackgroundImage.size; [homeBtn addTarget:self action:@selector(home) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:homeBtn]; viewController.navigationItem.rightBarButtonItem = rightItem; viewController.hidesBottomBarWhenPushed = YES; } [super pushViewController:viewController animated:animated]; } // 弹出当前控制器 - (void)back { [self popViewControllerAnimated:YES]; } // 弹出到根控制器 - (void)home { [self popToRootViewControllerAnimated:YES]; } @end
最终效果: