Swift 專案總結 04 - 自定義控制器轉場
自定義控制器轉場
自定義控制器轉場包括 Push 轉場、Tabs 切換轉場和 Modal 轉場,在日常的專案開發中都十分常用,而這些轉場動畫通常是具有通用性的,所以我在專案開發中採用建立轉場代理類來實現。
下面以 Push 為例說明,其他轉場型別同理:
1. 建立轉場代理類 CustomTransitionDelegate
,繼承 NSObject
2. 繼承 UINavigationControllerDelegate
協議並實現下面的協議方法
// 返回處理 push/pop 轉場動畫物件,就是對應上面那個表格的代理方法
func navigationController(
_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
3. 繼承 UIViewControllerAnimatedTransitioning
協議並實現下面的協議方法
// 返回轉場動畫時間
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
// 執行動畫呼叫
func animateTransition(using transitionContext: UIViewControllerContextTransitioning)
4.【重要】必須在你自定義轉場動畫結束時呼叫 UIViewControllerContextTransitioning
上下文物件轉場完成
transitionContext.completeTransition(true)
5. 控制器屬性持有該轉場代理類物件
class ViewController: UIViewController {
// 自定義的轉場代理
fileprivate var customTransitionDelegate = CustomTransitionDelegate()
}
6. 控制器轉場時設定該代理物件(不同情況)
// UITabBarController + Tab
self.tabBarController?.delegate = customTransitionDelegate
// UINavigationController + Push
func pushWithCustomTransition() {
guard let navigationController = self.navigationController else { return }
let pushVc = PushViewController()
navigationController.delegate = customTransitionDelegate
navigationController.pushViewController(pushVc, animated: true)
}
// UIViewController + Modal
func presentWithCustomTransition() {
let modalController = ModalViewController()
modalController.transitioningDelegate = customTransitionDelegate
self.transitioningDelegate = customTransitionDelegate
self.present(modalController, animated: true, completion: nil)
}
以下是我實現的具體3種自定義控制器轉場代理類例子,分別執行3種動畫:漸變、卡片彈出、點擴散,其中漸變轉場代理類實現了3種型別轉場,其他2個只實現了 Modal 型別轉場
漸變轉場代理類
class AlphaTransitionDelegate: NSObject, UIViewControllerAnimatedTransitioning {
// 自定義屬性,判斷是出現還是消失
fileprivate var isAppear: Bool = true
/// UIViewControllerTransitioningDelegate 代理方法,返回轉場動畫時間
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if self.isAppear {
return 0.45
} else {
return 0.40
}
}
/// UIViewControllerTransitioningDelegate 代理方法,處理轉場執行動畫
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if self.isAppear {
animateTransitionForAppear(using: transitionContext)
} else {
animateTransitionForDisappear(using: transitionContext)
}
}
/// 自定義方法,處理出現的轉場動畫
fileprivate func animateTransitionForAppear(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
let duration = self.transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
containerView.addSubview(fromView)
containerView.addSubview(toView)
// 漸變動畫
toView.alpha = 0
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
toView.alpha = 1.0
}, completion: { (_) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
/// 自定義方法,處理消失的轉場動畫
fileprivate func animateTransitionForDisappear(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
let duration = self.transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
containerView.insertSubview(toView, at: 0)
// 漸變動畫
fromView.alpha = 1.0
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
fromView.alpha = 0
}, completion: { (_) in
fromView.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
// MARK: - UITabBarControllerDelegate 分頁轉場代理
extension AlphaTransitionDelegate: UITabBarControllerDelegate {
/// 返回處理 tabs 轉場動畫的物件
func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isAppear = true
return self
}
}
// MARK: - UINavigationControllerDelegate 導航轉場代理
extension AlphaTransitionDelegate: UINavigationControllerDelegate {
/// 返回處理 push/pop 轉場動畫的物件
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
isAppear = true
case .pop:
isAppear = false
default:
return nil
}
return self
}
}
// MARK: - UIViewControllerTransitioningDelegate 彈出轉場代理
extension AlphaTransitionDelegate: UIViewControllerTransitioningDelegate {
/// 返回處理 present 轉場動畫的物件
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// presented 被彈出的控制器,presenting 根控制器,source 源控制器
self.isAppear = true
return self
}
/// 返回處理 dismiss 轉場動畫的物件
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isAppear = false
return self
}
}
卡片轉場代理類
class CardTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
// 自定義屬性,判斷是 present 還是 dismiss
fileprivate var isPresent: Bool = true
fileprivate weak var maskBackgroundView: UIView?
fileprivate weak var source: UIViewController?
fileprivate weak var presented: UIViewController?
// 動畫卡片距離頂部的距離
fileprivate var topForShow: CGFloat = 40
init(topForShow: CGFloat) {
super.init()
self.topForShow = topForShow
}
/// 代理方法,返回處理 present 轉場動畫的物件
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// presented - 被彈出控制器,presenting - 根控制器(Navigation/Tab/View),source - 源控制器
// 因為使用了 overFullScreen,source 不會呼叫 viewWillDisappear 和 viewDidDisappear,這裡手動觸發
source.viewWillDisappear(false)
source.viewDidDisappear(false)
self.source = source
self.presented = presented
self.isPresent = true
return self
}
/// 代理方法,返回處理 dismiss 轉場動畫的物件
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresent = false
return self
}
/// 代理方法,返回 present 或者 dismiss 的轉場時間
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if self.isPresent { // present
return 0.45
} else { // dismiss
return 0.45
}
}
/// 代理方法,處理 present 或者 dismiss 的轉場,這裡分離出 2 個子方法分別處理 present 和 dismiss
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if self.isPresent { // present
animateTransitionForPresent(using: transitionContext)
} else { // dismiss
animateTransitionForDismiss(using: transitionContext)
}
}
/// 自定義方法,處理 present 轉場
fileprivate func animateTransitionForPresent(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
let duration = self.transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
containerView.addSubview(fromView)
// 灰色背景控制元件
let maskBackgroundView = UIView(frame: containerView.bounds)
maskBackgroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
maskBackgroundView.alpha = 0.0
maskBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CardTransitionDelegate.clickMaskViewAction(_:))))
self.maskBackgroundView = maskBackgroundView
fromView.addSubview(maskBackgroundView)
containerView.addSubview(toView)
// 動畫開始,底層控制器往後縮小,灰色背景漸變出現,頂層控制器從下往上出現
let tranformScale = (UIScreen.main.bounds.height - self.topForShow) / UIScreen.main.bounds.height
let tranform = CGAffineTransform(scaleX: tranformScale, y: tranformScale)
toView.frame.origin.y = UIScreen.main.bounds.height
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
toView.frame.origin.y = self.topForShow
maskBackgroundView.alpha = 1.0
fromView.transform = tranform
}, completion: { (_) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
/// 自定義方法,處理 dismiss 轉場
fileprivate func animateTransitionForDismiss(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
let duration = self.transitionDuration(using: transitionContext)
// 動畫還原
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
fromView.frame.origin.y = UIScreen.main.bounds.height
self.maskBackgroundView?.alpha = 0.0
toView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}, completion: { (_) in
self.maskBackgroundView?.removeFromSuperview()
// 注意!:因為外面使用了 overFullScreen ,dismiss 會丟失檢視,需要自己手動加上
UIApplication.shared.keyWindow?.insertSubview(toView, at: 0)
// 因為使用了 overFullScreen,導致 source 沒法正常呼叫 viewWillAppear 和 viewDidAppear,這裡手動觸發
if let source = self.source {
source.viewWillAppear(false)
source.viewDidAppear(false)
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
/// 點選灰色背景事件處理
func clickMaskViewAction(_ gestureRecognizer: UITapGestureRecognizer) {
self.presented?.dismiss(animated: true, completion: nil)
}
}
點擴散轉場代理類
class RippleTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
// 自定義屬性,判斷是 present 還是 dismiss
fileprivate var isPresent: Bool = true
fileprivate weak var transitionContext: UIViewControllerContextTransitioning?
// 起始點座標
var startOrigin: CGPoint = CGPoint.zero
// 擴散半徑
fileprivate var radius: CGFloat = 0
init(startOrigin: CGPoint = .zero) {
super.init()
self.startOrigin = startOrigin
// 這裡取擴散最大半徑,即螢幕的對角線長
let screenWidth = ceil(UIScreen.main.bounds.size.width)
let screenHeight = ceil(UIScreen.main.bounds.size.height)
self.radius = sqrt((screenWidth * screenWidth) + (screenHeight * screenHeight))
}
/// 代理方法,返回處理 present 轉場動畫的物件
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresent = true
return self
}
/// 代理方法,返回處理 dismiss 轉場動畫的物件
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresent = false
return self
}
/// 代理方法,返回 present 或者 dismiss 的轉場時間
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if self.isPresent { // present
return 0.45
} else { // dismiss
return 0.40
}
}
/// 代理方法,處理 present 或者 dismiss 的轉場,這裡分離出 2 個子方法分別處理 present 和 dismiss
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
if self.isPresent { // present
animateTransitionForPresent(using: transitionContext)
} else { // dismiss
animateTransitionForDismiss(using: transitionContext)
}
}
/// 自定義方法,處理 present 轉場
fileprivate func animateTransitionForPresent(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
let duration = self.transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
containerView.addSubview(fromView)
containerView.addSubview(toView)
// 計算動畫圖層開始和結束路徑
let startFrame = CGRect(origin: self.startOrigin, size: .zero)
let maskStartPath = UIBezierPath(ovalIn: startFrame)
let maskEndPath = UIBezierPath(ovalIn: startFrame.insetBy(dx: -self.radius, dy: -self.radius))
// 建立動畫圖層, layer.mask 屬性是表示顯示的範圍
let maskLayer = CAShapeLayer()
maskLayer.path = maskEndPath.cgPath
toView.layer.mask = maskLayer
// 為動畫圖層新增路徑,從一個點開始擴散到整屏
let maskLayerAnimation = CABasicAnimation(keyPath: "path")
maskLayerAnimation.fromValue = maskStartPath.cgPath
maskLayerAnimation.toValue = maskEndPath.cgPath
maskLayerAnimation.duration = duration
maskLayerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
maskLayerAnimation.delegate = self
maskLayer.add(maskLayerAnimation, forKey: "ripple_push_animation")
}
/// 自定義方法,處理 dismiss 轉場
fileprivate func animateTransitionForDismiss(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
let duration = self.transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
containerView.insertSubview(toView, at: 0)
// 計算動畫圖層開始和結束路徑
let startFrame = CGRect(origin: self.startOrigin, size: .zero)
let maskStartPath = UIBezierPath(ovalIn: startFrame.insetBy(dx: -self.radius, dy: -self.radius))
let maskEndPath = UIBezierPath(ovalIn: startFrame)
// 建立動畫圖層,layer.mask 屬性是表示顯示的範圍
let maskLayer = CAShapeLayer()
maskLayer.path = maskEndPath.cgPath
fromView.layer.mask = maskLayer
// 為動畫圖層新增路徑,從整屏收縮到一個點
let maskLayerAnimation = CABasicAnimation(keyPath: "path")
maskLayerAnimation.fromValue = maskStartPath.cgPath
maskLayerAnimation.toValue = maskEndPath.cgPath
maskLayerAnimation.duration = duration
maskLayerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
maskLayerAnimation.delegate = self
maskLayer.add(maskLayerAnimation, forKey: "ripple_dimiss_animation")
}
}
// MARK: - CAAnimationDelegate
extension RippleTransitionDelegate: CAAnimationDelegate {
/// 動畫結束後呼叫
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
// 把 layer.mask 賦值為 nil,是為了釋放動畫圖層
if let transitionContext = self.transitionContext {
if let toViewController = transitionContext.viewController(forKey: .to) {
toViewController.view.layer.mask = nil
}
if let fromViewController = transitionContext.viewController(forKey: .from) {
fromViewController.view.layer.mask = nil
}
transitionContext.completeTransition(true)
}
}
}
這三個轉場代理類的 Demo 程式碼在這:
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/3034/viewspace-2801973/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Swift 專案總結 04 自定義控制器轉場Swift
- Swift 專案總結 03 自定義 CollectionView 佈局SwiftView
- 自定義TabBar動畫效果 - 頁面轉場(Swift)tabBar動畫Swift
- iOS Swift和OC專案中自定義LogiOSSwift
- Swift 專案總結 06 基於控制器的全域性狀態列管理Swift
- 自定義view總結View
- Swift 專案總結 02 常用分類方法Swift
- Swift 專案總結 01 Swift 反射應用於模型歸檔Swift反射模型
- TransitionAnimation自定義轉場動畫NaN動畫
- 自定義轉場動畫(二)動畫
- 自定義轉場動畫(一)動畫
- uniapp專案實踐總結(十六)自定義下拉重新整理元件APP元件
- Swift 自定義運算子Swift
- 建立自定義專案模板
- Flutter Widget自定義總結Flutter
- iOS自定義 Transitions 動畫總結iOS動畫
- 專案管理之---競投專案總結(轉)專案管理
- (轉)OC專案轉Swift指南Swift
- MD04 增加自定義列
- 一行程式碼實現自定義轉場動畫--iOS自定義轉場動畫集行程動畫iOS
- Swift中自定義運算子Swift
- swift4.0 自定義LOGSwift
- Swift 自定義 UIDatePickerSwiftUI
- .NET Core - 自定義專案模板
- Swift 專案總結 08 GIF 圖片載入優化Swift優化
- Swift 專案總結 07 檢視樣式可配置化Swift
- 軟體專案需求分析總結(轉)
- 【Vue專案總結】後臺管理專案總結Vue
- Windows XP 去掉“自定義通知”中的無用專案(轉)Windows
- BBS專案專案總結
- 自定義Push/Pop和Present/Dismiss轉場
- iOS自定義轉場動畫(push、pop動畫)iOS動畫
- 自定義present和dismiss的轉場動畫動畫
- 專案總結
- 自定義Swift版SegmentControlSwift
- Swift - 自定義Share分享頁面Swift
- 自定義身份證鍵盤(Swift)Swift
- 自定義View以及事件分發總結View事件