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

iOS 日曆翻頁動畫:做出四個對角都能翻的效果

編輯:iOS 開發綜合

本文談兩件事:日曆本身怎麼算,以及翻頁動畫怎麼做。

    1. 日曆(只講原理)

    2. 翻頁動畫(重點)

圖中沿四個對角方向的翻頁,對應各個方向的手勢滑動。

一、日曆的三個關鍵數字

要畫出一個月的月曆,其實只需要三個資訊:

    1. 今天幾號

    2. 這個月的第一天是星期幾

    3. 這個月總共有幾天

有了這三個數字,每個格子該顯示什麼日期就定了。至於用什麼呈現,個人偏好 UICollectionView,一個 cell 代表一天;用一堆 label 或 button 當然也做得到。

取得今天日期最簡單,NSDate() 即可。

取得本月第一天是星期幾,以下方法都寫成 NSDate 的 extension:

 // 本月第一天
 func firstDateOfCurrentMonth() -> NSDate {
     let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
     let currentDateComponents = calendar!.components([.Year, .Month], fromDate: self)
     let startOfMonth = calendar!.dateFromComponents(currentDateComponents)
     let date = startOfMonth?.dateByAddingTimeInterval(8 * 60 * 60)
     return date!
 }

 // 本月第一天是星期幾
 func firstDayOfCurrentMonth() -> Int {
     let calendar = NSCalendar.currentCalendar()
     let components = calendar.components(.Weekday, fromDate: firstDateOfCurrentMonth())
     return components.weekday - 1
 }

取得本月天數則可用 rangeOfDaysInMonth 一類的 API。日期相關的三個主要類別是 NSDate、NSCalendar、NSDateComponents,由於不是本文重點,這裡不展開。

二、翻頁動畫

這個效果屬於轉場動畫,可以用 CATransition 實作。只要設定時長、時間函數與 fillMode 就能得到動畫;其中 type 決定過渡樣式,subType 決定方向。不過官方預定義的 type 只有四種:

 NSString * const kCATransitionFade;
 NSString * const kCATransitionMoveIn;
 NSString * const kCATransitionPush;
 NSString * const kCATransitionReveal;

翻頁效果並不在其中。查了資料之後發現,直接把 type 設成 "pageCurl" 或 "pageUnCurl" 就能得到理想的效果——這兩個值並未出現在官方文件裡。

但預設情況下,往上翻只有左上角的動畫,往下翻只有右下角的動畫,做不出四個對角的效果。

解法是在最底層放一個 containerView,再把 dayView(也就是作為日曆的 collectionView)放進去。要往右上角翻時,先把 containerView 的 layer 沿 y 軸旋轉 M_PI,原本的右下角就變成左下角,翻頁方向自然變成右上;接著把 dayView 反向轉回來,這樣容器是反的、看到的日期卻是正的。左下角同理。

 // 為 dayView 加上滑動手勢
 func addPanGestureToDayView() {
     let swipe = UIPanGestureRecognizer(target: self, action: #selector(self.panOnDayView(_:)))
     dayView.addGestureRecognizer(swipe)
 }

 func panOnDayView(pan: UIPanGestureRecognizer) {
     // 手勢結束,且沒有其他動畫正在進行時才觸發
     if pan.state == .Ended && !animatiing {
         addAnimationToDayView(pan)
     }
 }

 let pageCurlDuration = 0.5
 let kPageCurlKey = "pageCurl"     // 往上翻
 let kPageUnCurlKey = "pageUnCurl" // 往下翻

 func addAnimationToDayView(pan: UIPanGestureRecognizer) {
     let translation = pan.translationInView(dayView)
     let transitioin = CATransition()
     transitioin.duration = pageCurlDuration
     transitioin.timingFunction = CAMediaTimingFunction(name: "default")
     // 這兩個屬性必須同時設定,動畫結束後狀態才不會被移除
     transitioin.fillMode = kCAFillModeForwards
     transitioin.removedOnCompletion = false
     // 用 delegate 在動畫開始/結束時做一些處理
     transitioin.delegate = self

     if translation.y < 0 {
         if translation.x > 0 {
             // 往右上翻:沿 y 軸旋轉 containerView,右下角變成左下角
             animationContainerView.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI), 0, 1, 0)
             // dayView 是加在 containerView 上的,必須反向轉回來才不會顛倒
             dayView.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI), 0, 1, 0)
         }
         transitioin.type = kPageCurlKey
         transitioin.subtype = kCATransitionFromBottom
         // 記下方向,動畫結束時才知道要切到哪個月
         transitioin.setValue("next", forKey: "month")
     } else {
         if translation.x < 0 {
             // 往左下翻,做法與右上相同
             animationContainerView.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI), 0, 1, 0)
             dayView.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI), 0, 1, 0)
         }
         transitioin.type = kPageUnCurlKey
         transitioin.subtype = kCATransitionFromTop
         transitioin.setValue("pre", forKey: "month")
     }
     dayView.layer.addAnimation(transitioin, forKey: "pageCurl")
 }

由於設定了 delegate,動畫的開始與結束都會回呼,可以在這兩個時機處理資料與狀態:

 override func animationDidStart(anim: CAAnimation) {
     animatiing = true
     let components = GregorianCalendar?.components([.Year, .Month, .Day], fromDate: date)
     if anim.valueForKey("month") as! String == "next" {
         components?.month += 1
     } else if anim.valueForKey("month") as! String == "pre" {
         components?.month -= 1
     }
     date = (GregorianCalendar?.dateFromComponents(components!))!
     dateDidChaged!(date: date)
 }

 override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
     if flag {
         animatiing = false
         // 復原 transform 並移除動畫,避免影響下一次翻頁
         animationContainerView.layer.transform = CATransform3DIdentity
         dayView.layer.transform = CATransform3DIdentity
         dayView.layer.removeAnimationForKey("pageCurl")
     }
 }

小結

翻頁動畫其實還有別的做法,這裡選這個方案純粹是因為要支援四個對角。如果對 CATransition 的屬性還不熟,建議先把 fillMode 與 removedOnCompletion 的關係弄清楚,動畫結束後畫面殘留或閃現的問題多半都出在這裡。

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