用 CABasicAnimation 改變 opacity 從 1.0 到 0.0,動畫結束後 UIImageView 仍佔據佈局空間(可見但透明),需手動隱藏。
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
anim.duration = 1.0;
anim.fromValue = @1.0;
anim.toValue = @0.0;
[flowerImageView.layer addAnimation:anim forKey:@"animateOpacity"];
// 動畫結束後隱藏
[NSTimer scheduledTimerWithTimeInterval:anim.duration
target:self
selector:@selector(hideImageView)
userInfo:nil
repeats:NO];
- (void)hideImageView {
flowerImageView.hidden = YES;
}
[CATransaction begin];
[CATransaction setCompletionBlock:^{
flowerImageView.hidden = YES;
}];
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
anim.duration = 1.0;
anim.fromValue = @1.0;
anim.toValue = @0.0;
[flowerImageView.layer addAnimation:anim forKey:@"animateOpacity"];
[CATransaction commit];
[UIView animateWithDuration:1.0
animations:^{
flowerImageView.alpha = 0.0;
}
completion:^(BOOL finished) {
flowerImageView.hidden = YES;
}];
| 方案 | 精準度 | 程式碼量 | 適用場景 |
|---|---|---|---|
| NSTimer | 約略(可能早/晚幾幀) | 少 | 快速原型 |
| CATransaction | 逐幀精準 | 中 | Core Animation 直接操作屬性 |
| UIView animate | 逐幀精準 | 最少 | 一般 alpha/frame/transform 動畫 |
[flowerImageView removeFromSuperview]。viewWillAppear 重設 hidden = NO; alpha = 1.0。UIViewPropertyAnimator 獲得更細緻控制。推薦 **UIView animateWithDuration:completion:**,一行搞定動畫與隱藏,碼簡且精準。