UIView 動畫的本質是「將屬性變更包裝在動畫區塊中」,由 UIKit 自動計算插值並渲染。經典 API 流程:
[UIView beginAnimations:@"View Flip" context:nil];
[UIView setAnimationDuration:1.25];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
// 這裡修改可動畫屬性(frame、alpha、transform、backgroundColor 等)
[self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
[UIView commitAnimations];
| 方法 | 用途 | 關鍵參數 |
|---|---|---|
beginAnimations:context: | 開始動畫區塊 | animationID(識別碼)、context(傳遞給代理) |
commitAnimations | 提交並啟動動畫 | — |
setAnimationDuration: | 設定持續時間(秒) | 預設 0.2 |
setAnimationDelay: | 設定延遲啟動(秒) | 預設 0.0 |
setAnimationCurve: | 設定緩動曲線 | EaseInOut(預設)、EaseIn、EaseOut、Linear |
setAnimationTransition:forView:cache: | 設定轉場效果 | Flip、Curl、CrossDissolve 等 |
setAnimationDelegate: | 設定代理物件 | 接收 start/stop 回調 |
setAnimationWillStartSelector: | 動畫開始回調 | selector 簽名需含 animationID、context |
setAnimationDidStopSelector: | 動畫結束回調 | selector 簽名:animationFinished:finished:context: |
setAnimationRepeatCount: | 重複次數 | 可為小數,預設 0(不重複) |
setAnimationRepeatAutoreverses: | 來回重複 | YES/NO,需配合 repeatCount |
setAnimationBeginsFromCurrentState: | 從當前狀態開始 | YES:打斷當前動畫無縫銜接 |
setAnimationStartDate: | 指定開始時間 | NSDate,預設立即 |
areAnimationsEnabled | 查詢動畫是否啟用 | 回傳 BOOL |
setAnimationsEnabled: | 全域啟用/停用動畫 | YES/NO |
- (void)viewDidLoad {
[super viewDidLoad];
self.blueController = [[BlueViewController alloc] initWithNibName:nil bundle:nil];
self.blueController.view.frame = self.view.bounds;
self.yellowController = [[YellowController alloc] initWithNibName:nil bundle:nil];
self.yellowController.view.frame = self.view.bounds;
[self.view insertSubview:self.blueController.view atIndex:0];
[self.view insertSubview:self.yellowController.view atIndex:1]; // 最上層
self.rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"Next"
style:UIBarButtonItemStylePlain
target:self
action:@selector(buttonPressed)];
self.navigationItem.rightBarButtonItem = self.rightBarItem;
}
- (void)buttonPressed {
[self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
[UIView beginAnimations:@"View Flip" context:nil];
[UIView setAnimationDuration:1.25];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
[UIView commitAnimations];
}
原因: App 啟動時系統有預設動畫,兩者衝突導致自訂動畫被吞噬。
解決:
performSelector:withObject:afterDelay: 延遲執行NSTimer 延遲一幀舊版 API 已不建議新專案使用。現代寫法更簡潔、支援完成閉包:
[UIView animateWithDuration:1.25
delay:0
options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionTransitionCurlUp
animations:^{
[self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}
completion:^(BOOL finished) {
// 動畫結束後處理
}];
layerClass 可自訂 View 底層 CALayer 類別(預設 CALayer),進階動畫建議直接操作 CALayer 或使用 CAAnimation 子類別。