前一段時間換了工作,項目趕得緊,文章就擱下了,現在閒下來趕緊補一篇。今天集中處理導航欄的各種問題,從系統默認行為說起,一路講到自定義返回按鈕、全屏滑動返回,最後是切換動畫的方案。
默認情況下,導航欄左上角的返回按鈕,其文案取自上一個 ViewController 的 title;若上一級沒有設置 title,則顯示 Back(中文環境為「返回」)。點擊返回和右滑返回都不需要任何配置,這部分沒有太多可說的。
絕大多數項目都要替換返回按鈕。這件事本身不難,但有幾個細節值得注意。
創建一個 UIButton,包成 UIBarButtonItem 掛到 leftBarButtonItem 上即可:
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
leftBtn.frame = CGRectMake(0, 0, 25, 25);
[leftBtn setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
[leftBtn addTarget:self action:@selector(leftBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
}
- (void)leftBarBtnClicked:(UIButton *)btn {
[self.navigationController popViewControllerAnimated:YES];
}
上面這種寫法,按鈕會偏右一點。想讓它貼近屏幕左緣,直接改 frame 是行不通的——NavigationItem 是個比較特殊的容器,沒法用簡單的 frame 調整來定位左右按鈕。
的解法是借 UIBarButtonSystemItemFixedSpace,把一個固定寬度的間距項放在按鈕前面,寬度取負值:
// 返回按鈕
UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
leftBtn.frame = CGRectMake(0, 0, 25, 25);
[leftBtn setBackgroundImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
[leftBtn addTarget:self action:@selector(leftBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftBarBtn = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
// 負寬度的間距項
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
target:nil
action:nil];
spaceItem.width = -15;
self.navigationItem.leftBarButtonItems = @[spaceItem, leftBarBtn];
這樣返回按鈕就緊貼屏幕邊緣了。同樣的手法也適用於右側按鈕。
替換系統返回按鈕後,經常會發現側滑返回手勢失效。解法是重新指定 interactivePopGestureRecognizer 的代理:讓 ViewController 遵守 UIGestureRecognizerDelegate,然後:
self.navigationController.interactivePopGestureRecognizer.delegate = self;
這是非常常見的需求,網上方案很多,這裡貼的是我常用的做法。核心思路:拿到系統滑動手勢的 target,創建一個自己的 pan 手勢複用它的 action,然後禁用系統手勢。
// 取得系統手勢的 target
id target = self.interactivePopGestureRecognizer.delegate;
// 自建全屏 pan,直接調用系統的切換方法
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target
action:@selector(handleNavigationTransition:)];
pan.delegate = self;
[self.view addGestureRecognizer:pan];
// 關掉系統自帶的邊緣手勢
self.interactivePopGestureRecognizer.enabled = NO;
原理就這麼簡單。handleNavigationTransition: 是系統內部的方法,雖然沒有公開接口,但可以直接調用,不必擔心私有 API 的問題——如果 Apple 按方法名判定私有 API,誤傷的 App 數量會非常可觀。
不想看長文的同學可以直接跳到最后看集成方式。
換好樣式、做好全屏返回之後,導航欄看著還不錯,但切換時仍然是系統自帶的漸變動畫。一旦前一屏的 NavigationBar 是透明或隱藏的,或者前後兩屏的 Bar 顏色差異較大,這個漸變就非常難看。
天貓、美團等 App 的解法是把導航欄「整體返回」:整個頁面連同導航欄一起平移,而不是只動內容區。這樣兩個 NavigationBar 相互獨立,滑動切換中的各種狀態錯亂問題也就不復存在。
實現這個效果大致有三條思路:
setNavigationBarHidden:animated:,在 viewWillDisappear: 隱藏、viewWillAppear: 顯示;Push 前截圖存數組,Pop 時取出顯示,滑動結束後調用系統 Pop 並刪除截圖。UIViewControllerAnimatedTransitioning 協議,自定義轉場動畫與交互。方法一非常繁瑣,還會冒出各種難以定位的問題,直接放棄。
另外要區分兩種場景:Push 一般由按鈕點擊或 cell 的 tap 觸發,屬於「無交互」;Pop 既可能來自返回按鈕,也可能來自右滑手勢,屬於「有交互」。下面分別用方法二和方法三來實現,兩者配合基本能覆蓋所有情況。
准備工作
#define ScreenWidth [UIScreen mainScreen].bounds.size.width #define ScreenHeight [UIScreen mainScreen].bounds.size.height @interface LTNavigationController ()@property (strong, nonatomic) UIImageView *screenshotImgView; // 截圖 @property (strong, nonatomic) UIView *coverView; // 半透明遮罩 @property (strong, nonatomic) NSMutableArray *screenshotImgs; // 截圖棧 @property (strong, nonatomic) UIPanGestureRecognizer *panGestureRec; @end @implementation LTNavigationController - (void)viewDidLoad { [super viewDidLoad]; // 1. 側滑手勢,只響應左緣 _panGestureRec = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRec:)]; _panGestureRec.edges = UIRectEdgeLeft; [self.view addGestureRecognizer:_panGestureRec]; // 2. 截圖視圖(frame 包含狀態欄高度) _screenshotImgView = [[UIImageView alloc] init]; _screenshotImgView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight); // 3. 黑色半透明遮罩 _coverView = [[UIView alloc] init]; _coverView.frame = _screenshotImgView.frame; _coverView.backgroundColor = [UIColor blackColor]; // 4. 截圖棧 _screenshotImgs = [NSMutableArray array]; }
手勢響應
- (void)panGestureRec:(UIPanGestureRecognizer *)panGestureRec {
// 已經是根控制器,無需切換
if (self.visibleViewController == self.viewControllers[0]) return;
switch (panGestureRec.state) {
case UIGestureRecognizerStateBegan:
[self dragBegin];
break;
case UIGestureRecognizerStateEnded:
[self dragEnd];
break;
default:
[self dragging:panGestureRec];
break;
}
}
// 遮罩初始透明度
#define kDefaultAlpha 0.6
// 拖動達到屏寬 3/4 時,遮罩完全消失
#define kTargetTranslateScale 0.75
#pragma mark - 開始拖動
- (void)dragBegin {
// 每次開始都要把截圖和遮罩插到 window 上
[self.view.window insertSubview:_screenshotImgView atIndex:0];
[self.view.window insertSubview:_coverView aboveSubview:_screenshotImgView];
_screenshotImgView.image = [_screenshotImgs lastObject];
}
#pragma mark - 拖動中
- (void)dragging:(UIPanGestureRecognizer *)pan {
CGFloat offsetX = [pan translationInView:self.view].x;
// 整個導航界面跟手右移
if (offsetX > 0) {
self.view.transform = CGAffineTransformMakeTranslation(offsetX, 0);
}
// 截圖以較慢的速度跟隨,形成視差
if (offsetX < ScreenWidth) {
_screenshotImgView.transform = CGAffineTransformMakeTranslation((offsetX - ScreenWidth) * 0.6, 0);
}
// 遮罩隨位移線性變透明
double currentScale = offsetX / self.view.frame.size.width;
_coverView.alpha = kDefaultAlpha - (currentScale / kTargetTranslateScale) * kDefaultAlpha;
}
#pragma mark - 結束拖動
- (void)dragEnd {
CGFloat translateX = self.view.transform.tx;
CGFloat width = self.view.frame.size.width;
if (translateX <= 40) {
// 位移不足,彈回
[UIView animateWithDuration:0.3 animations:^{
self.view.transform = CGAffineTransformIdentity;
_screenshotImgView.transform = CGAffineTransformMakeTranslation(-ScreenWidth, 0);
_coverView.alpha = kDefaultAlpha;
} completion:^(BOOL finished) {
[_screenshotImgView removeFromSuperview];
[_coverView removeFromSuperview];
}];
} else {
// 位移足夠,完成返回
[UIView animateWithDuration:0.3 animations:^{
self.view.transform = CGAffineTransformMakeTranslation(width, 0);
_screenshotImgView.transform = CGAffineTransformMakeTranslation(0, 0);
_coverView.alpha = 0;
} completion:^(BOOL finished) {
// 動畫結束後必須歸零 transform,否則下次拖動會錯亂
self.view.transform = CGAffineTransformIdentity;
[_screenshotImgView removeFromSuperview];
[_coverView removeFromSuperview];
[self popViewControllerAnimated:NO];
}];
}
}
截圖與 Push 時機
- (void)screenShot {
UIViewController *beyondVC = self.view.window.rootViewController;
CGSize size = beyondVC.view.frame.size;
UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
CGRect rect = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
// iOS 7 之後 renderInContext: 已由 drawViewHierarchyInRect:afterScreenUpdates: 取代
[beyondVC.view drawViewHierarchyInRect:rect afterScreenUpdates:NO];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
if (snapshot) { [_screenshotImgs addObject:snapshot]; }
UIGraphicsEndImageContext();
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
// 棧裡已有子控制器時才需要截圖
if (self.viewControllers.count >= 1) {
[self screenShot];
}
[super pushViewController:viewController animated:YES];
}
重寫各個 Pop 方法
截圖棧的維護要和實際的返回層級對應。如果直接調用 popToViewController: 或 popToRootViewControllerAnimated:,要刪的就不止一張:
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
[_screenshotImgs removeLastObject];
return [super popViewControllerAnimated:animated];
}
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated {
for (NSInteger i = self.viewControllers.count - 1; i > 0; i--) {
if (viewController == self.viewControllers[i]) { break; }
[_screenshotImgs removeLastObject];
}
return [super popToViewController:viewController animated:animated];
}
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated {
[_screenshotImgs removeAllObjects];
return [super popToRootViewControllerAnimated:animated];
}
在指定頁面屏蔽手勢
上面用的是側滑手勢。之所以不用全屏,是因為全屏手勢在某些場景會和系統手勢衝突——比如 TableView 的左滑刪除。如果衝突的是自定義手勢還好協調,撞上系統手勢就很頭疼。
如果產品確實要求全屏,可以在特定控制器裡關掉手勢。做法是維護一個禁用名單:
@property (nonatomic, copy) NSArray *forbiddenArray;
- (void)viewDidLoad {
[super viewDidLoad];
self.panGestureRec.enabled = YES;
self.forbiddenArray = @[@"SCViewController", @"ManageAddressViewController"];
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
BOOL enable = YES;
NSString *className = NSStringFromClass([viewController class]);
for (NSString *string in self.forbiddenArray) {
if ([string isEqualToString:className]) { enable = NO; }
}
self.panGestureRec.enabled = enable;
[super pushViewController:viewController animated:animated];
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
NSInteger count = self.viewControllers.count;
BOOL enable = YES;
if (count >= 2) {
NSString *className = NSStringFromClass([self.viewControllers[count - 2] class]);
for (NSString *string in self.forbiddenArray) {
if ([string isEqualToString:className]) { enable = NO; }
}
}
self.panGestureRec.enabled = enable;
return [super popViewControllerAnimated:animated];
}
這部分要請出 UIViewControllerAnimatedTransitioning。先明確目標效果:
Pop 的實現步驟
Push 的實現步驟
為什麼 Push 要動導航欄?
Push 動畫開始之前,我們無法知道 ToVC 具體長什麼樣——系統截屏方法對尚未渲染的 view 無能為力,而 snapshotViewAfterScreenUpdates: 又沒法把導航欄一起映射到新 view 上,視覺效果很差。而在 Pop 場景中,為了達到效果,兩張展示圖片本來就得放在導航欄的 view 上。所以 Push 時索性把導航欄 view 做一個平移變換,截圖則放到「更上一層」的 UITabbarController 的 view 上。
動畫控制器代碼
- (void)animateTransition:(id)transitionContext {
UIImageView *screentImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
screentImgView.image = [self screenShot];
UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
CGRect fromViewEndFrame = [transitionContext finalFrameForViewController:fromViewController];
fromViewEndFrame.origin.x = ScreenWidth;
CGRect toViewEndFrame = [transitionContext finalFrameForViewController:toViewController];
CGRect toViewStartFrame = toViewEndFrame;
UIView *containerView = [transitionContext containerView];
NSTimeInterval duration = [self transitionDuration:transitionContext];
if (self.navigationOperation == UINavigationControllerOperationPush) {
[self.screenShotArray addObject:screentImgView.image];
[containerView addSubview:toView];
toView.frame = toViewStartFrame;
UIView *nextVC = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, ScreenHeight)];
nextVC.layer.shadowColor = [UIColor blackColor].CGColor;
nextVC.layer.shadowOffset = CGSizeMake(-0.8, 0);
nextVC.layer.shadowOpacity = 0.6;
[self.navigationController.tabBarController.view insertSubview:screentImgView atIndex:0];
self.navigationController.view.transform = CGAffineTransformMakeTranslation(ScreenWidth, 0);
[UIView animateWithDuration:duration animations:^{
self.navigationController.view.transform = CGAffineTransformMakeTranslation(0, 0);
screentImgView.center = CGPointMake(-ScreenWidth / 2, ScreenHeight / 2);
} completion:^(BOOL finished) {
[nextVC removeFromSuperview];
[screentImgView removeFromSuperview];
[transitionContext completeTransition:YES];
}];
}
if (self.navigationOperation == UINavigationControllerOperationPop) {
[containerView addSubview:toView];
UIImageView *lastVcImgView = [[UIImageView alloc] initWithFrame:CGRectMake(-ScreenWidth, 0, ScreenWidth, ScreenHeight)];
lastVcImgView.image = [self.screenShotArray lastObject];
screentImgView.layer.shadowColor = [UIColor blackColor].CGColor;
screentImgView.layer.shadowOffset = CGSizeMake(-0.8, 0);
screentImgView.layer.shadowOpacity = 0.6;
[self.navigationController.tabBarController.view addSubview:lastVcImgView];
[self.navigationController.tabBarController.view addSubview:screentImgView];
[UIView animateWithDuration:duration animations:^{
screentImgView.center = CGPointMake(ScreenWidth * 3 / 2, ScreenHeight / 2);
lastVcImgView.center = CGPointMake(ScreenWidth / 2, ScreenHeight / 2);
} completion:^(BOOL finished) {
[lastVcImgView removeFromSuperview];
[screentImgView removeFromSuperview];
[self.screenShotArray removeLastObject];
[transitionContext completeTransition:YES];
}];
}
}
- (void)removeLastScreenShot {
[self.screenShotArray removeLastObject];
}
- (UIImage *)screenShot {
UIViewController *beyondVC = self.navigationController.view.window.rootViewController;
CGSize size = beyondVC.view.frame.size;
UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
CGRect rect = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
[beyondVC.view drawViewHierarchyInRect:rect afterScreenUpdates:NO];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshot;
}
注意:removeLastScreenShot 需要在使用手勢 Pop 之後調用,用來清理動畫控制器裡保存的截圖。否則交互式與非交互式動畫交替使用時,會出現截圖錯位混亂的問題。
這篇文章斷斷續續寫了四個月,中間因為個人和工作的原因一再拖延,最近才補完,邏輯跳躍之處還請包容。
集成方式
把這四個文件導入工程,然後讓你的導航控制器繼承 KTNavigationController 即可,無需額外配置。