ios - CABasicAnimation byValue 奇怪的行为

标签 ios swift core-animation

我正在阅读 12th number of Objc.io并在尝试第一段代码时遇到问题。 在第一部分“基本动画”中,最后一段代码使用 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

最佳答案

你应该像这样为这个动画创建一个完成 block :

@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 block ,因为我们有 2 个动画以彼此不同的时间运行。

关于ios - CABasicAnimation byValue 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383747/

相关文章:

ios - 应用程序未运行/应用程序终止时如何处理推送通知

ios - 图像目录中矢量 pdf 的渲染模式设置为模板,但 UIImageView 不会在自定义单元格中为图像着色

iOS自定义键盘模板背景颜色为图像

ios - 将经过的 TimeInterval 添加到 Date()

ios - 圆角,同时将 subview 扩展到父 View 的边界之外

iOS仿射旋转只工作一次

ios - 带有 CGAffineTransformMakeScale 的 UIView 动画会立即用十进制数更改大小

ios - 如何过滤包含字符串和数组的结构?

swift - 我可以让 SKSpriteNode 在过渡期间显示在不同的场景上吗

ios - 如何获取Show segue的计时功能和时长