在隐式动画期间,CALayer'丢失'从外部类设置的值

时间:2015-01-09 12:07:04

标签: animation swift calayer

我在Swift中的自定义属性上有一个带隐式动画的CLLayer。 从类内部我可以在动画期间访问我的属性的插值。但是当我使用我从类外部设置的其他属性时,它们在动画期间没有值。当动画结束时,原始值再次可用。

因此,在下面的示例中,人们有五个随机值,这些值在drawInContext中打印到控制台,但是当动画运行时,人们是空的

这是我的自定义CALayer

class BackgroundLayer: CALayer {

    @NSManaged var range: Double
    var people: []

    override class func needsDisplayForKey(key: String) -> Bool {
        if key == "range" {
            return true
        }
        return super.needsDisplayForKey(key)
    }

    override func drawInContext(ctx: CGContext!) {

        let center = CGPoint(x: Double(bounds.width)/2, y: Double(bounds.height)-bottomOffset)
        let xDist = Double(bounds.width)
        let yDist = Double(bounds.height)-bottomOffset-minRadius
        let maxDistance = sqrt(pow(xDist,2) + pow(yDist,2))
        let radius = CGFloat(minRadius + range * maxDistance)

        CGContextSetFillColorWithColor(ctx, UIColor(red: 208/255, green: 2/255, blue: 27/255, alpha: 1).CGColor)
        CGContextFillEllipseInRect(ctx, CGRectMake(center.x-radius, center.y-radius, radius*2, radius*2))

        println("are there people? \(people)")
    }

    override func actionForKey(event: String!) -> CAAction! {

        if event == "range" {
            var currentValue = self.presentationLayer().valueForKey(event) as Double
            if currentValue == 0 {
                currentValue = self.range
            }
            var rangeAnim = CABasicAnimation(keyPath: event)
            rangeAnim?.fromValue = currentValue
            rangeAnim?.duration = 0.5
            return rangeAnim
        }

        return super.actionForKey(event)
    }
}

这就是我在UIViewController中使用它来设置五个随机值

的方法
class ViewController: UIViewController {

    private let backgroundLayer = BackgroundLayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        for index in 0..<5 {

            println()
            let point = (x: Double(arc4random_uniform(UInt32(view.frame.width))), y: Double(arc4random_uniform(UInt32(view.frame.height))))
            backgroundLayer.people.append(point)
        }
        println(backgroundLayer.people)
    }

    override func viewWillLayoutSubviews() {
        backgroundLayer.contentsScale = UIScreen.mainScreen().scale
        backgroundLayer.frame = self.view.frame
        self.view.layer.addSublayer(backgroundLayer)
        backgroundLayer.setNeedsDisplay()
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        backgroundLayer.range = 1
    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        backgroundLayer.range = 0
    }
}

0 个答案:

没有答案