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

标签 ios swift core-animation

我将这个场景与 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/

相关文章:

iphone - UIButton 标记未在 6 个单元格后分配 indexPath.row

ios - 如何向 UICollectionViewCell 内的标签添加约束?

iphone - 在 iOS 上,自定义 View 不会设置动画?

ios - 检查应用程序是否在 App Store 中评级

ios - 重用 CollectionViewController 是一种好习惯,还是创建另一个更好?

ios - 多个 Storyboard - 多个导航 Controller

swift - 使用 Calendar.date 时时区错误

ios - 混合 V.S.离屏渲染,哪个对 Core Animation 性能更差?

iphone - 使用 CATransform3D 将矩形图像转换为四边形

ios - Swift URLSession 完成处理程序