如何重新启动CALayer动画,而它正在进行中



我使用这个场景与UIView的动画没有问题,但不能让它与CALayer动画工作。

我做了一个游乐场来演示这个问题:

import UIKit
import PlaygroundSupport
class EventHandler {
    @objc func onClick(_ button: UIButton) {
        button.layer.removeAllAnimations()
        button.layer.borderColor = UIColor.red.cgColor
        print("RED")
        CATransaction.begin()
        CATransaction.setCompletionBlock({
            button.layer.borderColor = UIColor.black.cgColor
            print("BLACK")
        })
        let colorAnimation = CABasicAnimation()
        colorAnimation.toValue = UIColor.black.cgColor
        colorAnimation.duration = 5
        button.layer.add(colorAnimation, forKey: "borderColor")
        CATransaction.commit()
    }
}
let eventHandler = EventHandler()
let button = UIButton(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200))
button.backgroundColor = UIColor.gray
button.layer.borderColor = UIColor.black.cgColor
button.layer.borderWidth = 20
button.addTarget(eventHandler, action: #selector(EventHandler.onClick(_:)), for: .touchDown)
PlaygroundPage.current.liveView = button

我想要的是当我点击动画中间的按钮时,动画应该重新开始。但似乎当我调用removeAllAnimations()时,原始动画的完成块不是在我将颜色设置为RED之前执行,而是在它之后执行。

通过为动画对象设置fromValue修复了这个问题。下面是工作版本:

import UIKit
import PlaygroundSupport
class EventHandler {
    @objc func onClick(_ button: UIButton) {
        button.layer.removeAllAnimations()
        let colorAnimation = CABasicAnimation()
        colorAnimation.fromValue = UIColor.red.cgColor
        colorAnimation.toValue = UIColor.black.cgColor
        colorAnimation.duration = 5
        button.layer.add(colorAnimation, forKey: "borderColor")   
    }
}
let eventHandler = EventHandler()
let button = UIButton(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200))
button.backgroundColor = UIColor.gray
button.layer.borderColor = UIColor.black.cgColor
button.layer.borderWidth = 20
button.addTarget(eventHandler, action: #selector(EventHandler.onClick(_:)), for: .touchDown)
PlaygroundPage.current.liveView = button

最新更新