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];從 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 寫法通常更有效率。若需要與多個回呼或舊有程式碼相容,再考慮類方法寫法。