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

iOS UIView 動畫:類方法與 Block 兩種寫法

編輯:iOS 開發綜合

UIView 動畫基礎

UIView 動畫是 iOS 中最常見的動畫方式之一,本質上是對 CALayer 動畫的封裝。開發者只要改變 view 的最終狀態,UIKit 就會在指定時間內補上中間動畫。

類方法寫法

早期常用 beginAnimations 與 commitAnimations 搭配使用。它可以設定動畫時間、延遲、曲線、重複次數與代理回呼。

[UIView beginAnimations:@"animation" context:nil];
[UIView setAnimationDuration:10];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
anim.frame = CGRectMake(100, 100, 50, 50);
[UIView commitAnimations];

Block 寫法

從 iOS 4 開始,更常用的是 animateWithDuration:animations:completion:。寫法更直覺,也更容易組合多個動畫步驟。

[UIView animateWithDuration:5 animations:^{
    anim.frame = CGRectMake(100, 100, 50, 50);
}];

若需要在動畫完成後做事,可以加上 completion。

[UIView animateWithDuration:5 animations:^{
    anim.frame = CGRectMake(200, 200, 50, 50);
    anim.backgroundColor = [UIColor grayColor];
} completion:^(BOOL finished) {
    NSLog(@"動畫完成");
}];

兩種寫法比較

類方法寫法較傳統,適合需要細部控制動畫代理的情境;Block 寫法更簡潔,適合大多數日常動畫需求。兩者都能透過參數設定 duration、delay、curve 與 repeat 等屬性。

小結

若只是簡單的位移、尺寸或透明度變化,Block 寫法通常更有效率。若需要與多個回呼或舊有程式碼相容,再考慮類方法寫法。

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