UIView 動畫系統是 iOS 交互體驗的核心。本文系統梳理塊語法、關鍵參數、彈性動畫、鏈式組合與性能優化。
[UIView animateWithDuration:0.5
delay:0
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
// 可動畫屬性:frame, bounds, center, transform, alpha, backgroundColor, contentOffset 等
self.view.alpha = 0;
self.button.transform = CGAffineTransformMakeScale(1.2, 1.2);
} completion:^(BOOL finished) {
// 動畫完成回調
[self.view removeFromSuperview];
}];
frame、bounds、center、transform(旋轉/縮放/傾斜)alpha、backgroundColor、tintColorcontentOffset、contentInset(ScrollView)⚠️ 不可動畫: layer.cornerRadius、layer.shadow*、font、text、bounds.size 直接賦值(需用 transform)。
| 選項 | 行為 |
|---|---|
UIViewAnimationOptionCurveEaseInOut | 慢-快-慢(默認) |
UIViewAnimationOptionCurveLinear | 勻速 |
UIViewAnimationOptionCurveEaseIn | 慢開始 |
UIViewAnimationOptionCurveEaseOut | 慢結束 |
UIViewAnimationOptionRepeat | 循環 |
UIViewAnimationOptionAutoreverse | 往返(需配合 Repeat) |
UIViewAnimationOptionAllowUserInteraction | 動畫期間允許用戶交互 |
UIViewAnimationOptionLayoutSubviews | 動畫中佈局子視圖 |
UIViewAnimationOptionBeginFromCurrentState | 從當前狀態開始(打斷前一動畫) |
[UIView animateWithDuration:0.6
delay:0
usingSpringWithDamping:0.6 // 0~1,越小彈性越大
initialSpringVelocity:0.8 // 初始速度
options:UIViewAnimationOptionAllowUserInteraction
animations:^{
self.cardView.center = targetCenter;
} completion:nil];
模擬物理彈簧效果,極大提升交互質感(如彈出菜單、卡片翻轉)。
// 序列:嵌套 completion
[UIView animateWithDuration:0.3 animations:^{
self.view.alpha = 0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 animations:^{
self.otherView.alpha = 1;
}];
}];
// 並行:同時啟動多個動畫塊
[UIView animateWithDuration:0.3 animations:^{
self.view1.alpha = 0;
}];
[UIView animateWithDuration:0.3 animations:^{
self.view2.transform = CGAffineTransformMakeTranslation(100, 0);
}];
// 關鍵幀動畫 (CAKeyframeAnimation) - 複雜軌跡
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
anim.values = @[[NSValue valueWithCGPoint:start], [NSValue valueWithCGPoint:mid], [NSValue valueWithCGPoint:end]];
anim.keyTimes = @[@0, @0.5, @1];
anim.duration = 1.0;
[self.layer addAnimation:anim forKey:@"path"];
- (IBAction)togglePanel:(id)sender {
CGFloat targetY = self.isExpanded ? self.collapsedY : self.expandedY;
[UIView animateWithDuration:0.4
delay:0
usingSpringWithDamping:0.8
initialSpringVelocity:0
options:UIViewAnimationOptionAllowUserInteraction
animations:^{
self.panelView.center = CGPointMake(self.panelView.center.x, targetY);
self.toggleButton.transform = self.isExpanded ? CGAffineTransformIdentity : CGAffineTransformMakeRotation(M_PI);
} completion:^(BOOL finished) {
self.isExpanded = !self.isExpanded;
}];
}
view.layer.shouldRasterize = YES; view.layer.rasterizationScale = [UIScreen mainScreen].scale; 靜態複雜視圖動畫前開啟,動畫後關閉。layoutSubviews,預先計算好終態 Frame/Transform。transform 不觸發佈局,GPU 直接合成,效能更高。view.layer.drawsAsynchronously = YES 針對繪制複雜視圖。動畫不只是「會動」,更要「動得順、動得準、動得省」。