CABasicAnimation byValue奇怪的行为

时间:2015-05-21 20:28:03

标签: ios swift core-animation

我正在阅读12th number of Objc.io并在尝试第一段代码时遇到问题。 在第一部分" A Basic Animation"最后一段代码使用byValue使用初始属性值插入属性并添加byValue。

所以我在我的项目中尝试了代码,发现它没有工作,并且有一种非常奇怪的行为。

这是一个非常简短的GIF,说明了这个问题:

Gif video illustrating the bug

这是我使用的唯一代码:

class ViewController: UIViewController {

    var rocket1: UIView!
    var rocket2: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        rocket1 = UIView(frame: CGRect(x: 20, y: 100, width: 50, height: 20))
        rocket1.backgroundColor = UIColor.redColor()
        rocket2 = UIView(frame: CGRect(x: 20, y: 150, width: 50, height: 20))
        rocket2.backgroundColor = UIColor.blueColor()

        self.view.addSubview(rocket1)
        self.view.addSubview(rocket2)

    }

    @IBAction func button() {
        let animation = CABasicAnimation(keyPath: "position.x")
        animation.byValue = 300
        animation.duration = 1

        rocket1.layer.addAnimation(animation, forKey: "basic")
        rocket1.layer.position.x += 300

        animation.beginTime = CACurrentMediaTime() + 0.5

        rocket2.layer.addAnimation(animation, forKey: "basic")
        rocket2.layer.position.x += 300

    }
}

如果您想在这里尝试项目整个项目(使用iPhone 6模拟器或形状将被隐藏,因为5S也是"短"):https://dl.dropboxusercontent.com/u/378166/VCoreAnimation.zip

1 个答案:

答案 0 :(得分:1)

你应该为这个动画创建一个完成块,如下所示:

@IBAction func button() {
    let animation = CABasicAnimation(keyPath: "position.x")
    animation.byValue = 300
    animation.duration = 1

    CATransaction.begin()
    CATransaction.setCompletionBlock({
        rocket1.layer.position.x += 300
    })
    rocket1.layer.addAnimation(animation, forKey: "basic")
    CATransaction.commit()

    animation.beginTime = CACurrentMediaTime() + 0.5

    CATransaction.begin()
    CATransaction.setCompletionBlock({
        rocket2.layer.position.x += 300
    })
    rocket2.layer.addAnimation(animation, forKey: "basic")
    CATransaction.commit()
}

在这种情况下,我们需要2个CATransaction块,因为我们有2个动画相互运行时间不同。