2015-04-01 101 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] 
    } 
}