gpt4 book ai didi

ios - 如何在进行中重新启动 CALayer 动画?

转载 作者:行者123 更新时间:2023-11-28 16:05:06 25 4
gpt4 key购买 nike

我将这个场景与 UIView 的动画一起使用没有问题,但无法让它与 CALayer 动画一起工作。

我做了一个 Playground 来演示这个问题:

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() 时,原始动画的完成 block 不是在我将颜色设置为红色之前而是在它之后执行的。

最佳答案

通过将 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

关于ios - 如何在进行中重新启动 CALayer 动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com