對同一 UIImageView 同時執行兩個動畫:透明度從 0 變到 1(淡入),位置從當前點移動到目標點。動畫需在視圖加載完成後同時開始。
iOS UIView 動畫塊內的多屬性修改默認並行執行,只需在同一 animations block 中設置多個可動畫屬性。
UIImageView *imageView = ...; // 目標視圖
CGPoint targetPoint = CGPointMake(200, 300); // 目標位置
// 初始狀態:透明、原位置
imageView.alpha = 0.0f;
imageView.center = CGPointMake(50, 50); // 起始位置
// 同時執行淡入 + 位移動畫
[UIView animateWithDuration:2.0
delay:0.0
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
// 同時修改多個可動畫屬性,系統自動並行
imageView.center = targetPoint; // 位移動畫
imageView.alpha = 1.0f; // 淡入動畫
} completion:^(BOOL finished) {
// 動畫完成回調
NSLog(@"動畫完成:%@", finished ? @"YES" : @"NO");
// 後續邏輯:移除視圖、觸發下一步等
}];
| 屬性 | 類型 | 效果 |
|---|---|---|
| frame / bounds / center | CGRect / CGPoint | 位置、大小變化 |
| alpha | CGFloat (0~1) | 透明度漸變 |
| transform | CGAffineTransform | 旋轉、縮放、傾斜 |
| backgroundColor | UIColor | 背景顏色漸變 |
| contentScaleFactor | CGFloat | 內容縮放(慎用) |
若兩個動畫需不同持續時間、延遲、緩動曲線,需分別創建動畫:
// 動畫1:位移 2秒 線性
[UIView animateWithDuration:2.0 delay:0 options:UIViewAnimationOptionCurveLinear
animations:^{ imageView.center = targetPoint; }
completion:nil];
// 動畫2:淡入 1秒 延遲0.5秒 緩入緩出
[UIView animateWithDuration:1.0 delay:0.5 options:UIViewAnimationOptionCurveEaseInOut
animations:^{ imageView.alpha = 1.0f; }
completion:nil];
UIPropertyAnimator *animator = [[UIViewPropertyAnimator alloc]
initWithDuration:2.0
curve:UIViewAnimationCurveEaseInOut
animations:^{
imageView.center = targetPoint;
imageView.alpha = 1.0f;
}];
animator.addCompletionHandler(^ (UIViewAnimatingPosition finalPosition) {
NSLog(@"完成");
});
[animator startAnimation];
// 優勢:可暫停、恢復、反轉、調整進度、交互式控制
// 位移動畫
CABasicAnimation *moveAnim = [CABasicAnimation animationWithKeyPath:@"position"];
moveAnim.fromValue = [NSValue valueWithCGPoint:imageView.layer.position];
moveAnim.toValue = [NSValue valueWithCGPoint:targetPoint];
moveAnim.duration = 2.0;
// 透明度動畫
CABasicAnimation *fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnim.fromValue = @0.0f;
fadeAnim.toValue = @1.0f;
fadeAnim.duration = 2.0;
// 組合動畫組
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = @[moveAnim, fadeAnim];
group.duration = 2.0;
group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[imageView.layer addAnimation:group forKey:@"moveAndFade"];
// 注意:CALayer 動畫不改變模型層屬性,需手動設置最終值
imageView.layer.position = targetPoint;
imageView.layer.opacity = 1.0f;
UIView.animateWithDuration 一個 block 搞定。UIViewPropertyAnimator。CALayer + CAAnimation。viewDidLayoutSubviews 或 layoutIfNeeded 後)。viewDidLoad 中直接啟動動畫,視圖可能未顯示。