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

iOS 開發之十一:三種常用的畫面切換動畫實作

編輯:iOS 開發綜合

作者:Andy-清風。在 iOS 開發中,我們常需要在不同頁面之間做切換動畫,讓過場不至于生硬。最基本的三類做法分別是 UIView 動畫、CATransition,以及私有動畫。

1. UIView 動畫

UIKit 官方提供五種轉場效果:

  • UIViewAnimationTransitionNone:不使用動畫。
  • UIViewAnimationTransitionFlipFromLeft:由左翻轉而來。
  • UIViewAnimationTransitionFlipFromRight:由右翻轉而來,與前者相反。
  • UIViewAnimationTransitionCurlUp:由下往上捲頁。
  • UIViewAnimationTransitionCurlDown:由上往下捲頁。
[JUIView beginAnimations:@"animationID" context:nil]; // 開始一個動畫區塊,參數為標識

[JUIView setAnimationDuration:0.5f]; // 動畫持續時間

[JUIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; // 變化曲線,預設即為此值

[JUIView setAnimationRepeatAutoreverses:NO]; // 是否自動反向重播

[JUIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                       forView:self.view
                         cache:YES]; // 指定轉場效果

[self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0]; // 視圖翻轉

[JUIView commitAnimations]; // 提交動畫

這裡的順序有嚴格要求:setAnimationCurve 等設定必須夾在 beginAnimations 與 commitAnimations 之間,寫到外面不會有任何效果。cache 設為 YES 時,系統會先把視圖渲染成快取影像再翻轉,效能較好,適合內容靜態的場合。

2. CATransition

QuartzCore 提供四種轉場型別:

NSString * const kCATransitionFade;   // 淡出淡入
NSString * const kCATransitionMoveIn; // 覆蓋推入
NSString * const kCATransitionPush;   // 推出
NSString * const kCATransitionReveal; // 揭開,與 MoveIn 方向相反
CATransition *animation = [CATransition animation]; // 建立動畫

animation.duration = 0.5f;
animation.timingFunction = UIViewAnimationCurveEaseInOut;

animation.type = kCATransitionPush; // 指定上面四種之一

animation.subtype = kCATransitionFromTop; // 方向:FromRight / FromLeft / FromTop / FromBottom

[self.view.layer addAnimation:animation forKey:@"animationID"];

使用 CATransition 前別忘了引入 QuartzCore.framework。相較於 UIView 動畫,CATransition 是作用在 layer 層級,因此任何有 layer 的物件都能套用,不限於 view 的整體切換。

3. 私有動畫(Private API 轉場)

在 CATransition 的基礎上,把 animation.type 換成以下字串,就能取得更多效果:

  • cube:像立方體一樣翻面。
  • suckEffect:逐漸縮小消失,類似 iOS 刪除照片的過場。
  • oglFlip:上下翻轉;當 subtype 為 fromLeft/fromRight 時,效果等同 UIViewAnimationTransitionFlipFromLeft/Right。
  • rippleEffect:水波漣漪。
  • pageCurl:等同 UIViewAnimationTransitionCurlUp。
  • pageUnCurl:等同 UIViewAnimationTransitionCurlDown。
  • cameraIrisHollowOpen:相機光圈張開的前半段。
  • cameraIrisHollowClose:相機光圈關閉的後半段。

務必留意:這些屬於未公開的私有 API。在 App Store 審核中,靜態分析有機會偵測到私有介面的使用而被退件,因此正式產品請優先採用 UIView 動畫與 CATransition 的公開轉場;私有動畫較適合用在個人專案、Demo 或企業內部簽發的應用上。

三種做法的取捨很單純:只是換 view 的顯示與隱藏,用 UIView 動畫最省事;要對任意 layer 做轉場,用 CATransition;想要相機光圈、水波這類特殊視覺,才需要冒風險動用私有 API。

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