自定義導航控制器的核心目標,是把導航列上那些各頁面共用的部分抽出來統一設定,避免每個控制項都重複寫一遍。通常有三件事要做:
1、導航列標題的字型(setTitleTextAttributes:)與背景圖(setBackgroundImage:)多半是全域一致的,可以在 load 方法中透過 appearanceWhenContainedIn: 統一設定。
2、返回按鈕需要自訂。一般除了堆疊底層的控制器,其餘頁面都要顯示返回按鈕並隱藏底部 TabBar,這可以藉由覆寫 pushViewController:animated: 達成。
3、右滑返回手勢要能更靈活地觸發——理想狀態是觸摸螢幕任意位置向右滑動都能返回,而不僅限於螢幕邊緣。
先來看 navigationItem 的結構,自訂時基本都在這幾個屬性上做文章:
UIViewController
└─ navigationItem
├─ leftBarButtonItem | leftBarButtonItems
├─ NSString title | UIView titleView
├─ rightBarButtonItem | rightBarButtonItems
└─ backBarButtonItem
完整實作如下:
#import "BWNavigationController.h"
#import "UIBarButtonItem+Item.h"
@interface BaseNavigationController () <UIGestureRecognizerDelegate>
@end
@implementation BWNavigationController
+ (void)load {
[super load];
UINavigationBar *navigationBar = [UINavigationBar appearanceWhenContainedIn:self, nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSFontAttributeName] = [UIFont boldSystemFontOfSize:20];
[navigationBar setTitleTextAttributes:dict];
[navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackgroundWhite"]
forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 系統自帶的是螢幕邊緣滑動手勢
UIScreenEdgePanGestureRecognizer *edgePanGestureRecognizer =
(UIScreenEdgePanGestureRecognizer *)self.interactivePopGestureRecognizer;
// 改用自訂的平移手勢,目的是讓螢幕任意位置右滑都能返回
UIPanGestureRecognizer *panGestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:edgePanGestureRecognizer.delegate
action:@selector(handleNavigationTransition:)];
panGestureRecognizer.delegate = self;
[self.view addGestureRecognizer:panGestureRecognizer];
// 停用系統的螢幕邊緣滑動手勢
edgePanGestureRecognizer.enabled = NO;
}
// 是否允許觸發手勢:根視圖控制器不需要
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldReceiveTouch:(UITouch *)touch {
return self.childViewControllers.count > 1;
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
// 統一設定返回按鈕
NSInteger count = self.childViewControllers.count;
if (count > 0) {
viewController.hidesBottomBarWhenPushed = YES;
viewController.navigationItem.leftBarButtonItem =
[UIBarButtonItem backBarButtonItemWithImage:[UIImage imageNamed:@"navigationButtonReturn"]
highlightImage:[UIImage imageNamed:@"navigationButtonReturnClick"]
tagert:self
action:@selector(back)
title:@"返回"];
}
[super pushViewController:viewController animated:animated];
}
- (void)back {
[self popViewControllerAnimated:YES];
}
@end
幾個值得注意的細節:load 中設定的外觀是全域生效的,適合放共用的樣式;覆寫 push 時用 childViewControllers.count > 0 判斷是否為非根控制器,是決定要不要顯示返回按鈕的關鍵;而手勢部分藉由複用系統 edgePan 的 delegate 來調用 handleNavigationTransition:,可以避免自己重新實作轉場動畫。