首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UIImageView 漸隱動畫結束後自動隱藏

     編輯:程式設計綜合問答

問題

用 CABasicAnimation 改變 opacity 從 1.0 到 0.0,動畫結束後 UIImageView 仍佔據佈局空間(可見但透明),需手動隱藏。

方案一:NSTimer 延遲隱藏(簡單但非精準)

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 完成區塊(推薦,精準同步)

[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 動畫封裝(最輕量)

[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。
  • iOS 10+ 可用 UIViewPropertyAnimator 獲得更細緻控制。

推薦 **UIView animateWithDuration:completion:**,一行搞定動畫與隱藏,碼簡且精準。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved