實際開發中為了兼顧使用者體驗與個人化需求,往往需要自訂手勢返回。iOS 7 之後系統已內建這個能力,但有幾個明顯限制:需要 iOS 7.0 以上、手勢必須從螢幕左緣啟動、拖拽效果無法自訂。
本文示範打造一個自有的導航框架,支援 iOS 5.0 以上、觸摸起點可自訂、動畫效果完全可控,實作思路參考淘寶 App 的導航交互。
// // WHC_NavigationController.h // #import <UIKit/UIKit.h> #define KWHC_Nav_Main_VC_Name (@"MyTabBarVC") // 主控制器類名 #define KWHC_Nav_Touch_Back_Rate (0.4) // 觸摸拖拽可以返回的條件比例 #define KWHC_Nav_Pop_Form_Border (-1) // note: > 0 從邊緣出發;< 0 任意位置出發(距離 > 30) @interface WHC_NavigationController : UINavigationController // 單例,預設用 KWHC_Nav_Main_VC_Name 作為主控制器 + (instancetype)sharedInstance; // 單例,自訂主控制器 + (instancetype)sharedInstanceWithMainVC:(UIViewController *)mainVC; @end
//
// WHC_NavigationController.m
//
#import "WHC_NavigationController.h"
#define KWHC_NAV_LEFT_VIEW_TAG (203994850) // 左邊 view 的 tag
#define KWHC_NAV_LEFT_PUSH_VIEW_TAG (KWHC_NAV_LEFT_VIEW_TAG + 1) // 左邊 pushView 的 tag
#define KWHC_NAV_NAVBAR_TAG (KWHC_NAV_LEFT_VIEW_TAG + 2) // 導航條的 tag
#define KWHC_NAV_ANIMATION_DURING (0.3) // pop 或 push 動畫週期
#define KWHC_NAV_POP_VIEW_CENTERX_OFFSET (0) // popView 中心 x 軸偏移(禁止修改)
#define KWHC_NAV_PUSH_VIEW_CENTERX_OFFSET (0) // pushView 中心 x 偏移(禁止修改)
#define KWHC_NAV_POP_VIEW_ALPHA (0.5) // popView 透明度係數
#define KWHC_NAV_ALLOW_PULL_DISTANCE (30.0) // 可以拉開允許的距離
@interface WHC_NavigationController () <UINavigationControllerDelegate> {
UIPanGestureRecognizer *_panGesture; // 手勢
CGFloat _currentTx; // 存儲當前觸摸 x 值
NSMutableArray *_snapshootList; // 快照數組
UIView *_popView; // 彈出 view
UIView *_pushView; // 壓棧 view
UIView *_topView; // 頂部視圖
BOOL _willOpen; // 是否將要拉開
BOOL _didOpen; // 是否已經拉開
BOOL _isTouchPop; // 是否觸摸彈出
}
@end
static WHC_NavigationController *whc_navigation;
@implementation WHC_NavigationController
#pragma mark - 單例實現
+ (instancetype)sharedInstance {
UIViewController *rootVC = [[NSClassFromString(KWHC_Nav_Main_VC_Name) alloc] init];
return [WHC_NavigationController sharedInstanceWithMainVC:rootVC];
}
+ (instancetype)sharedInstanceWithMainVC:(UIViewController *)mainVC {
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
whc_navigation = [[WHC_NavigationController alloc] initWithRootViewController:mainVC];
whc_navigation.delegate = whc_navigation;
});
return whc_navigation;
}
#pragma mark - 初始化
// 重載父類各個初始化方法,確保手勢都被註冊
- (instancetype)initWithRootViewController:(UIViewController *)rootViewController {
self = [super initWithRootViewController:rootViewController];
if (self) {
[self registPanGesture:YES];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self != nil) {
[self registPanGesture:YES];
}
return self;
}
- (instancetype)init {
self = [super init];
if (self != nil) {
[self registPanGesture:YES];
}
return self;
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[self registPanGesture:YES];
}
return self;
}
#pragma mark - 手勢註冊
- (void)registPanGesture:(BOOL)b {
// 關閉系統內建的返回手勢,避免與自訂手勢衝突
self.interactivePopGestureRecognizer.enabled = NO;
if (b) {
if (_panGesture == nil) {
_panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:@selector(handlePanGesture:)];
[_panGesture delaysTouchesBegan];
[self.view addGestureRecognizer:_panGesture];
}
} else {
if (_panGesture != nil) {
[self.view removeGestureRecognizer:_panGesture];
_panGesture = nil;
}
}
}
#pragma mark - 手勢處理
- (void)handlePanGesture:(UIPanGestureRecognizer *)panGesture {
switch (panGesture.state) {
case UIGestureRecognizerStateBegan: {
_currentTx = self.view.transform.tx;
}
break;
case UIGestureRecognizerStateChanged: {
CGFloat moveDistance = [panGesture translationInView:panGesture.view].x;
if (!_willOpen) {
if (KWHC_Nav_Pop_Form_Border < 0) {
// 任意位置出發,但移動距離需超過閾值
if (moveDistance < KWHC_NAV_ALLOW_PULL_DISTANCE) {
return;
}
} else {
// 只能從邊緣出發
CGFloat touchX = [panGesture locationInView:panGesture.view].x;
if (touchX > KWHC_Nav_Pop_Form_Border) {
return;
}
}
}
CGFloat oriX = [panGesture velocityInView:panGesture.view].x;
CGFloat rate = moveDistance / CGRectGetWidth(self.view.frame);
if (oriX > 0) { // 拉開
[self popView];
if (!_willOpen && _popView != nil) {
UIView *oldPopView = [self.view.superview viewWithTag:KWHC_NAV_LEFT_VIEW_TAG];
if (oldPopView) {
[oldPopView removeFromSuperview];
}
[self.view.superview insertSubview:_popView belowSubview:self.view];
_willOpen = YES;
}
if (_willOpen && moveDistance >= 0.0) {
self.view.transform = [self initAffineTransform:moveDistance + _currentTx];
_popView.center = CGPointMake(KWHC_NAV_POP_VIEW_CENTERX_OFFSET
+ rate * CGRectGetWidth(_popView.frame) / 2.0,
_popView.center.y);
_popView.alpha = KWHC_NAV_POP_VIEW_ALPHA * (rate + 1.0);
}
} else if (oriX < 0 && _willOpen && moveDistance >= 0.0) {
// 反向收回
self.view.transform = [self initAffineTransform:moveDistance + _currentTx];
_popView.center = CGPointMake(KWHC_NAV_POP_VIEW_CENTERX_OFFSET
+ rate * CGRectGetWidth(_popView.frame) / 2.0,
_popView.center.y);
_popView.alpha = KWHC_NAV_POP_VIEW_ALPHA * (rate + 1.0);
} else if (_willOpen) {
if (moveDistance < 0.0 && self.view.transform.tx > 0) {
self.view.transform = [self initAffineTransform:0.0];
_popView.center = CGPointMake(KWHC_NAV_POP_VIEW_CENTERX_OFFSET, _popView.center.y);
_popView.alpha = KWHC_NAV_POP_VIEW_ALPHA;
}
}
}
break;
case UIGestureRecognizerStateCancelled:
case UIGestureRecognizerStateEnded: {
if (_willOpen) {
// 依拖拽比例決定要完成返回還是取消
if (self.view.transform.tx / CGRectGetWidth(self.view.frame) < KWHC_Nav_Touch_Back_Rate) {
[self closeLeftView:YES];
} else {
[self closeLeftView:NO];
}
}
}
break;
default:
break;
}
}
// 位移變換
- (CGAffineTransform)initAffineTransform:(CGFloat)x {
return CGAffineTransformMakeTranslation(x, 0.0);
}
// 對當前控制器進行快照
- (UIImage *)snapshootNavBar:(UIViewController *)vc {
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *snapshootImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshootImage;
}
// 取得要彈出 view 的快照
- (UIView *)popView {
if (_snapshootList != nil && _snapshootList.count > 1) {
_popView = [_snapshootList lastObject];
_popView.center = CGPointMake(KWHC_NAV_POP_VIEW_CENTERX_OFFSET, _popView.center.y);
_popView.alpha = KWHC_NAV_POP_VIEW_ALPHA;
} else {
_popView = nil;
}
return _popView;
}
// 取得已經 push 的快照 view
- (UIView *)pushView {
if (_snapshootList != nil && _snapshootList.count > 0) {
_pushView = [_snapshootList lastObject];
_pushView.center = CGPointMake(KWHC_NAV_PUSH_VIEW_CENTERX_OFFSET, _pushView.center.y);
_pushView.alpha = 1.0;
} else {
_pushView = nil;
}
return _pushView;
}
// 完成或取消 pop 操作
- (void)closeLeftView:(BOOL)isClose {
[self registPanGesture:NO];
_willOpen = NO;
UIView *mainView = self.view;
__weak typeof(self) sf = self;
if (isClose) {
// 取消返回,畫面歸位
[UIView animateWithDuration:KWHC_NAV_ANIMATION_DURING
delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
_popView.center = CGPointMake(KWHC_NAV_POP_VIEW_CENTERX_OFFSET, _popView.center.y);
_popView.alpha = KWHC_NAV_POP_VIEW_ALPHA;
mainView.transform = [sf initAffineTransform:0.0];
} completion:^(BOOL finished) {
[sf registPanGesture:YES];
[_popView removeFromSuperview];
_popView = nil;
}];
} else {
// 執行返回
[UIView animateWithDuration:KWHC_NAV_ANIMATION_DURING
delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
mainView.transform = [sf initAffineTransform:CGRectGetWidth(mainView.frame)];
_popView.center = CGPointMake(CGRectGetWidth(_popView.frame) / 2.0, _popView.center.y);
_popView.alpha = 1.0;
} completion:^(BOOL finished) {
[sf registPanGesture:YES];
_isTouchPop = YES;
mainView.transform = [sf initAffineTransform:0];
[sf popViewControllerAnimated:NO];
}];
}
}
#pragma mark - 生命週期
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - 重寫 push
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
if (_snapshootList == nil) {
_snapshootList = [NSMutableArray array];
}
[_snapshootList addObject:[[UIImageView alloc] initWithImage:[self snapshootNavBar:viewController]]];
[self pushView];
// 忽略第一次 push 操作
if (_pushView && animated && _snapshootList != nil) {
__weak typeof(self) sf = self;
// 防止重複 push
_topView = self.topViewController.view;
_topView.userInteractionEnabled = NO;
[super pushViewController:viewController animated:NO];
self.view.transform = [self initAffineTransform:CGRectGetWidth(self.view.frame)];
UIView *oldPushView = [self.view.superview viewWithTag:KWHC_NAV_LEFT_PUSH_VIEW_TAG];
if (oldPushView) {
[oldPushView removeFromSuperview];
oldPushView = nil;
}
_pushView.center = CGPointMake(CGRectGetWidth(_pushView.frame) / 2.0, _pushView.center.y);
[self.view.superview insertSubview:_pushView belowSubview:self.view];
[UIView animateWithDuration:KWHC_NAV_ANIMATION_DURING
delay:0
options:UIViewAnimationOptionCurveEaseIn
animations:^{
_pushView.center = CGPointMake(-CGRectGetWidth(_pushView.frame) / 2.0, _pushView.center.y);
_pushView.alpha = KWHC_NAV_POP_VIEW_ALPHA;
sf.view.transform = [sf initAffineTransform:0];
} completion:^(BOOL finished) {
[_pushView removeFromSuperview];
_pushView = nil;
}];
} else {
[super pushViewController:viewController animated:animated];
}
}
#pragma mark - 重寫 pop
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
UIViewController *viewController = nil;
if (!_isTouchPop) {
// 不是觸摸彈出操作,需要播放返回動畫
__weak typeof(self) sf = self;
__block UIView *popView = [[UIImageView alloc] initWithImage:[self snapshootNavBar:nil]];
viewController = [super popViewControllerAnimated:NO];
if (popView) {
self.view.transform = [self initAffineTransform:-CGRectGetWidth(self.view.frame)];
self.view.alpha = KWHC_NAV_POP_VIEW_ALPHA;
UIView *oldPopView = [self.view.superview viewWithTag:KWHC_NAV_LEFT_VIEW_TAG];
if (oldPopView) {
[oldPopView removeFromSuperview];
oldPopView = nil;
}
popView.center = CGPointMake(CGRectGetWidth(popView.frame) / 2.0, popView.center.y);
[self.view.superview insertSubview:popView belowSubview:self.view];
[UIView animateWithDuration:KWHC_NAV_ANIMATION_DURING
delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
popView.center = CGPointMake(CGRectGetWidth(popView.frame) * 1.5, popView.center.y);
sf.view.transform = [sf initAffineTransform:0];
sf.view.alpha = 1.0;
} completion:^(BOOL finished) {
[popView removeFromSuperview];
popView = nil;
[_snapshootList removeLastObject];
}];
}
} else {
// 觸摸彈出的情況:清除 popView 快照即可
[_snapshootList removeLastObject];
[_popView removeFromSuperview];
_popView = nil;
viewController = [super popViewControllerAnimated:animated];
}
_isTouchPop = NO;
return viewController;
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated {
}
- (void)navigationController:(UINavigationController *)navigationController
didShowViewController:(UIViewController *)viewController
animated:(BOOL)animated {
if (_topView != nil) {
_topView.userInteractionEnabled = YES;
}
}
@end

這套實作的核心技巧是「快照 + 位移」:每次 push 前先對畫面截圖存進陣列,返回時把上一頁的快照當作背景層,再用 transform 做視差位移,就不必依賴系統動畫。三個設計細節值得留意:用 __weak 打破 block 的循環引用、在動畫期間關閉 userInteractionEnabled 防止重複點擊、以及用 dispatch_once 保證導航物件唯一。若要接入專案,建議再把快照陣列加上數量上限,避免記憶體隨頁面層數線性增長。