我试图让一个非常基本的CAGradientLayer
动画工作。我有一个基本的2色CAGradientLayer
设置并添加到我的UIViewController
。
// Set up the gradient layer.
var gradientLayer: CAGradientLayer! {
let layer = CAGradientLayer()
layer.frame = self.view.bounds
layer.colors = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor]
layer.locations = [0.0, 1.0]
return layer
}
我正在尝试使用以下代码为其设置动画:
@IBAction func changeBackground(sender: AnyObject) {
let oldColors = self.gradientLayer.colors
let newColors = [UIColor.purpleColor().CGColor, UIColor.blueColor().CGColor]
self.gradientLayer.colors = newColors
let animation: CABasicAnimation = CABasicAnimation(keyPath: "colors")
animation.fromValue = oldColors
animation.toValue = newColors
animation.duration = 0.3
animation.removedOnCompletion = true
animation.fillMode = kCAFillModeForwards
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.delegate = self
self.gradientLayer.addAnimation(animation, forKey: "animateGradientColorChange")
}
但是,此代码不会对CAGradientLayer
产生任何变化。我在这里做错了什么?
答案 0 :(得分:4)
每次从layer
属性返回一个新的gradientLayer
对象。你需要稍微改变它,以便懒惰地启动它:
lazy var gradientLayer: CAGradientLayer! = {
let layer = CAGradientLayer()
layer.frame = self.view.bounds
layer.colors = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor]
layer.locations = [0.0, 1.0]
return layer
}()
为了完整起见,你原来的是一个计算属性,这意味着每次访问它时都会执行代码。使用延迟属性时,代码只在首次访问属性时执行一次,然后返回相同的对象。
这个游乐场可以观察到差异:
//: Playground - noun: a place where people can play
import UIKit
struct Dummy {
var gradientLayer: CAGradientLayer! {
let layer = CAGradientLayer()
layer.colors = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor]
layer.locations = [0.0, 1.0]
return layer
}
lazy var lazyGradientLayer: CAGradientLayer! = {
let layer = CAGradientLayer()
layer.colors = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor]
layer.locations = [0.0, 1.0]
return layer
}()
}
var dummy = Dummy()
let l1 = dummy.gradientLayer
let l2 = dummy.gradientLayer
let lazy1 = dummy.lazyGradientLayer
let lazy2 = dummy.lazyGradientLayer