2017-08-29 66 views
1

我有一個UIButton,按下它應該通過一組圖像爲其圖標設置動畫並在最後停止。點擊UIButton中的動畫圖標點擊

我有如下:

let loadingImages = (1...8).map { UIImage(named: "slice\($0)")! } 
    let animatedImage = UIImage.animatedImage(with: loadingImages, duration: 1.5) 
    sender.setImage(animatedImage, for: UIControlState.normal) 

設置圖像,我可以設置哪些可以在圖像設置爲最後圖像的計時器之後。但我認爲它不是非常精確,也不是很好的代碼。

有沒有更好的方法來將圖標從其初始狀態圖像1的30到最後30的圖像30停止動畫?

編輯:@ the4kman建議關閉此爲stop UIimageview animation at last image

它不是一個副本!該問題使用UIImageView,這個問題使用UIButton。這個問題是針對Objective-C的,這個問題是針對Swift 3的。它能解決我的問題嗎?不,現在有一個upvote的答案與我提出的使用計時器的答案相同。所以不,這是一個不同的問題!

+0

可能的複製 設置圖像視圖[停止的UIImageView動畫在最後圖像](https://stackoverflow.com/questions/29534518/stop-uiimageview-animation-at-last-image) – the4kman

回答

1

將UIImageView添加到按鈕是我能想到的最簡單的方法。但仍然檢測動畫完成是你需要處理的。我創建了一個UIImageView的子類,讓你知道動畫何時完成。

class AnimatedImageView: UIImageView, CAAnimationDelegate { 

    var completion: ((_ completed: Bool) -> Void)? 

    func startAnimate(completion: ((_ completed: Bool) -> Void)?) { 
     self.completion = completion 
     if let animationImages = animationImages { 
      let cgImages = animationImages.map({ $0.cgImage as AnyObject }) 
      let animation = CAKeyframeAnimation(keyPath: "contents") 
      animation.values = cgImages 
      animation.repeatCount = Float(self.animationRepeatCount) 
      animation.duration = self.animationDuration 
      animation.delegate = self 

      self.layer.add(animation, forKey: nil) 
     } else { 
      self.completion?(false) 
     } 
    } 

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { 
     completion?(flag) 
    } 
} 

這是如何使用將運行動畫,並把它添加到按鈕

var imageView: AnimatedImageView() 

...... 

let loadingImages = (1...8).map { UIImage(named: "slice\($0)")! } 
imageView.frame = button.bounds 
imageView.image = loadingImages.first 
imageView.animationImages = loadingImages 
imageView.animationDuration = 1.5 
imageView.animationRepeatCount = 1 
yourButton.addSubview(imageView) 

當按鈕被點擊的

imageView.startAnimate { (completed) in 
    imageView.image = images.last 
}