您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

iOS 實作 UINavigationController 全屏手勢返回的兩種方案

編輯:iOS 開發基礎

授權轉載,作者:ZeroJ

前言

其實 Apple 早就為 navigationController 內的每個頁面提供了從螢幕左緣往右滑動即可 pop 的系統手勢,頁面之間的轉場動畫也已經幫我們實作好了。不過現在越來越多 App 都加入了「全屏滑動返回」的互動——畢竟手機螢幕越做越大,從畫面任意位置滑動就能返回,操作起來確實方便許多。暫且不論這種交互設計的優劣,既然微博、QQ、簡書、網易新聞等眾多產品都在採用,那麼掌握它的實作方式自然就成了開發者的必備技能。

最終效果

先來看看最終的使用方式,整體來說相當直覺好用。

  • 第一種:直接使用自訂的 navigationController

如果你在 storyboard 裡開發,只要把 navigationController 的 class 換成自訂版本即可,它預設就具備全屏滑動返回能力。若某個頁面想關閉這個功能,在對應位置加上這行設定就行:

// 設置為true的時候開啟全屏滑動返回功能, 設置為false, 關閉    (navigationController as? CustomNavigationController)?.enabledFullScreenPop(isEnabled: false)

storyboard 中的設定方式如上圖所示。

若你偏好用程式碼初始化,直接以自訂的 navigationController 建立實例即可:

// 同樣的默認是開啟全屏滑動返回功能的 let navi = CustomNavigationController(rootViewController: rootVc) //如果需要關閉或者重新開啟, 在需要的地方使用下面方法 (navigationController as? CustomNavigationController)?.enabledFullScreenPop(isEnabled: false)
  • 第二種:使用 navigationController 的分類(Category)

這種做法預設不會自動開啟,需要由我們自行呼叫方法來啟用或關閉:

// 在需要的地方, 獲取到navigationController, 然後使用分類方法開啟(關閉)全屏返回手勢即可 navigationController?.zj_enableFullScreenPop(isEnabled: true)

實作思路: 實現全屏返回的方法有很多種。常見的一種是善用系統既有的手勢——透過 runtime 取得系統手勢的 target 與 selector,然後在分類或自訂 navigationController 上新增一個 pan 手勢,把它的 target 與 selector 指向 runtime 取到的系統手勢,這樣新的手勢便擁有與系統滑動返回完全一致的效果,實作起來相當省事。

不過本文想介紹的是另一種更貼近 Apple 推薦做法的方案:自訂轉場動畫。關於自訂轉場的種種知識,如果你還不熟悉,建議先讀讀我先前寫的轉場教學(那篇正是為本文做的鋪墊),裡面詳細示範了 present/dismiss 的用法。

  • 建立一個 ZJNavigationControllerDelegate,作為自訂 navigationController 的 delegate。

class ZJNavigationControllerDelegate: NSObject, UINavigationControllerDelegate {  let animator = ZJNavigationControllerAnimator()  let interactive = ZJNavigationControllerInteractiveTransition()  var panGesture: UIPanGestureRecognizer! = nil {      didSet {          interactive.panGesture = panGesture      }  }  func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {      interactive.navigationController = navigationController      animator.operation = operation      return animator  }  // 這裡是手勢交互動畫需要的對象  func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {      return interactive.isInteracting ? interactive : nil  } //    deinit { //        print("\(self.debugDescription) --- 銷毀") //    } }
  • 建立一個 ZJNavigationControllerAnimator,繼承自 NSObject 並實作 UIViewControllerAnimatedTransitioning 協議,負責具體的轉場動畫。

class ZJNavigationControllerAnimator: NSObject, UIViewControllerAnimatedTransitioning {   let duration = 0.35   var operation: UINavigationControllerOperation = .none   func transitionDuration(_ transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {       return duration   }   func animateTransition(_ transitionContext: UIViewControllerContextTransitioning) {       // fromVc 總是獲取到正在顯示在屏幕上的Controller       let fromVc = transitionContext.viewController(forKey: UITransitionContextFromViewControllerKey)!       // toVc 總是獲取到將要顯示的controller       let toVc = transitionContext.viewController(forKey: UITransitionContextToViewControllerKey)!       let containView = transitionContext.containerView()       let toView: UIView       let fromView: UIView       // Animators should not directly manipulate a view controller's views and should       // use viewForKey: to get views instead.       if transitionContext.responds(to:NSSelectorFromString("viewForKey:")) {           // 通過這種方法獲取到view不一定是對應controller.view           toView = transitionContext.view(forKey: UITransitionContextToViewKey)!           fromView = transitionContext.view(forKey: UITransitionContextFromViewKey)!       } else {           toView = toVc.view           fromView = fromVc.view       }       // 最終顯示在屏幕上的controller的frame       let visibleFrame = transitionContext.initialFrame(for: fromVc)       // 隱藏在右邊的controller的frame       let rightHiddenFrame = CGRect(origin: CGPoint(x: visibleFrame.width, y: visibleFrame.origin.y) , size: visibleFrame.size)       // 隱藏在左邊的controller的frame       let leftHiddenFrame = CGRect(origin: CGPoint(x: -visibleFrame.width/2, y: visibleFrame.origin.y) , size: visibleFrame.size)       if operation == .push {// push           toView.frame = rightHiddenFrame           fromView.frame = visibleFrame           //  添加toview到最上面(fromView是當前顯示在屏幕上的view不用添加)           containView.addSubview(toView)       } else {// pop           fromView.frame = visibleFrame           toView.frame = leftHiddenFrame           // 有時需要將toView添加到fromView的下面便於執行動畫           containView.insertSubview(toView, belowSubview: fromView)       }       UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: {           if self.operation == .push {                   toView.frame = visibleFrame                   fromView.frame = leftHiddenFrame           } else {                   fromView.frame = rightHiddenFrame                   toView.frame = visibleFrame           }       }) { (_) in           let cancelled = transitionContext.transitionWasCancelled()           if cancelled {                     // 如果中途取消了就移除toView(可交互的時候會發生)                     toView.removeFromSuperview()               }           // 通知系統動畫是否完成或者取消了(必須)           transitionContext.completeTransition(!cancelled)       }   } //    deinit { //        print("\(self.debugDescription) --- 銷毀") //    } }
  • 建立一個 ZJNavigationControllerInteractiveTransition,繼承自 UIPercentDrivenInteractiveTransition,用來處理手勢的互動過程。

UIPercentDrivenInteractiveTransition, 來處理手勢的過程 class ZJNavigationControllerInteractiveTransition: UIPercentDrivenInteractiveTransition {   var panGesture: UIPanGestureRecognizer! = nil {       didSet {           panGesture.addTarget(self, action: #selector(self.handlePan(gesture:)))       }   }   var containerView: UIView!   var navigationController: UINavigationController! = nil {       didSet {           containerView = navigationController.view           containerView.addGestureRecognizer(panGesture)       }   }   var isInteracting = false   override init() {       super.init()   }   func handlePan(gesture: UIPanGestureRecognizer) {       func finishOrCancel() {           let translation = gesture.translation(in: containerView)           let percent = translation.x / containerView.bounds.width           let velocityX = gesture.velocity(in: containerView).x           let isFinished: Bool           // 修改這裡可以改變手勢結束時的處理           if velocityX > 100 {               isFinished = true           } else if percent > 0.5 {               isFinished = true           } else {               isFinished = false           }           isFinished ? finish() : cancel()       }       switch gesture.state {       case .began:           isInteracting = true           // pop           if navigationController.viewControllers.count > 0 {               _ = navigationController.popViewController(animated: true)           }       case .changed:           if isInteracting {               let translation = gesture.translation(in: containerView)               var percent = translation.x / containerView.bounds.width               percent = max(percent, 0)               update(percent)           }       case .cancelled:           if isInteracting {               finishOrCancel()               isInteracting = false         }       case .ended:           if isInteracting {               finishOrCancel()               isInteracting = false         }       default:           break       }   } }
  • 最後,封裝自訂的 navigationController。

class CustomNavigationController: UINavigationController {   private(set) var panGesture: UIPanGestureRecognizer?   private var customDelegate: CustomNavigationControllerDelegate?   required init?(coder aDecoder: NSCoder) {       super.init(coder: aDecoder)       enabledFullScreenPop(isEnabled: true)   }   override init(rootViewController: UIViewController) {       super.init(rootViewController: rootViewController)       enabledFullScreenPop(isEnabled: true)   }   init() {       super.init(nibName: nil, bundle: nil)       enabledFullScreenPop(isEnabled: true)   }   // 開啟或者關閉全屏pop手勢(默認開啟)   func enabledFullScreenPop(isEnabled: Bool) {       if isEnabled {           if customDelegate == nil {               // 創建代理對象               customDelegate = CustomNavigationControllerDelegate()               // 創建手勢               panGesture = UIPanGestureRecognizer()               // 傳遞手勢給代理               customDelegate?.panGesture = panGesture               // 設置代理為自定義的               delegate = customDelegate           }       } else {           customDelegate = nil           panGesture = nil           delegate = nil       }   } }

至此,整個全屏滑動返回的實作就完成了。如果你對程式碼還有疑問,建議先補上自訂轉場動畫的基礎再回頭閱讀。使用效果如附圖所示。值得一提的是,本文並未特別處理頁面內含 scrollView 時可能出現的手勢衝突,這部分就留給有興趣的讀者自行嘗試。歡迎關注、歡迎 star,Demo 地址一併附上。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved