CALayer子类重复动画

时间:2015-04-01 14:37:58

标签: ios xcode swift core-animation

我试图创建一个每隔x秒执行一次动画的CALayer子类。在下面的示例中,我尝试将背景从一种随机颜色更改为另一种颜色,但在操场上运行时似乎没有发生任何事情

import UIKit
import XCPlayground
import QuartzCore

let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 200, height: 200))
XCPShowView("view", view)

class CustomLayer: CALayer {

    var colors = [
        UIColor.blueColor().CGColor,
        UIColor.greenColor().CGColor,
        UIColor.yellowColor().CGColor
    ]

    override init!() {
        super.init()

        self.backgroundColor = randomColor()

        let animation = CABasicAnimation(keyPath: "backgroundColor")

        animation.fromValue = backgroundColor
        animation.toValue = randomColor()
        animation.duration = 3.0
        animation.repeatCount = Float.infinity

        addAnimation(animation, forKey: "backgroundColor")

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    private func randomColor() -> CGColor {
        let index = Int(arc4random_uniform(UInt32(colors.count)))
        return colors[index]
    }
}

let layer = CustomLayer()
layer.frame = view.frame
view.layer.addSublayer(layer)

1 个答案:

答案 0 :(得分:1)

重复动画的参数只设置一次,因此您无法在每次重复时更改颜色。您应该实现委托方法,而不是重复动画, animationDidStop:finished:,然后使用新的随机颜色再次调用动画。我还没有在操场上试过这个,但它在应用程序中运行正常。请注意,除了你拥有的其他init方法之外,你还必须实现init!(layer layer:AnyObject!)。

import UIKit

class CustomLayer: CALayer {

    var newColor: CGColorRef!

    var colors = [
        UIColor.blueColor().CGColor,
        UIColor.greenColor().CGColor,
        UIColor.yellowColor().CGColor
    ]

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init!(layer: AnyObject!) {
        super.init(layer: layer)
    }

    override init!() {
        super.init()
        backgroundColor = randomColor()
        newColor = randomColor()
        self.animateLayerColors()
    }


    func animateLayerColors() {
        let animation = CABasicAnimation(keyPath: "backgroundColor")
        animation.fromValue = backgroundColor
        animation.toValue = newColor
        animation.duration = 3.0
        animation.delegate = self

        addAnimation(animation, forKey: "backgroundColor")
    }

    override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
        backgroundColor = newColor
        newColor = randomColor()
        self.animateLayerColors()
    }


    private func randomColor() -> CGColor {
        let index = Int(arc4random_uniform(UInt32(colors.count)))
        return colors[index]
    }
}