我在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之后执行,而是在它之后执行。
答案 0 :(得分:1)
通过将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