2015-04-01 63 views
0

我试图创建一个CALayer子类,每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) 
+0

从我所看到的情况来看,对于所有动画重复,您都有相同的“from”和“to”值。 – 2015-04-01 15:16:42

+0

问题是你根本没有得到任何动画? – 2015-04-01 15:18:33

+0

是的。没有动画发生。我随机获得一种颜色,没有任何颜色。 @DavidRönnqvist我明白你的意思,但是我将如何实施动画,以便为每次重复动画“请求”新颜色? – 2015-04-01 15:19:59

回答

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] 
    } 
}