我有一个 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)
设置图像后,我可以设置一个计时器,该计时器可以将图像设置为最后一张图像。但我认为它不是很准确,也不是很好的代码。
有没有更好的方法来使图标从其初始状态图像 30 张中的第 1 张动画化到它停止的最后一张图像 30 张中的最后一张图像?
编辑:@the4kman 建议将其关闭为 stop UIimageview animation at last image 的副本
不是!那道题用的是UIImageView,这道题用的是UIButton。这个问题是针对 Objective-C 的,这个问题是针对 Swift 3 的。它能解决我的问题吗?不,当前一次投票的答案与我建议自己使用计时器的答案相同。所以不,这是一个不同的问题!
最佳答案
在按钮上添加 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)
}
}
这是使用方法 设置将运行动画的 ImageView 并将其添加到按钮
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
}
关于ios - 单击 UIButton 中的动画图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45940981/