首页 > 解决方案 > AnimateKeyframes 同时运行所有关键帧 (Swift)

问题描述

我正在尝试为标签设置动画以在不同的关键帧使用不同的单词更改其文本,但它只是跳到最后一个关键帧(“晚安”)而不显示之前的关键帧。它确实将它们打印出来,所以我猜持续时间或 startTime 有问题,但我无法弄清楚它可能是什么..

func changeText() {

    let options = UIView.KeyframeAnimationOptions.calculationModeLinear

    UIView.animateKeyframes(withDuration: 10, delay: 0, options: options, animations: {

        UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: {
            self.label.text = "Good Morning"
            print("Morning")
        })

        UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: {
            self.label.text = "Good Afternoon"
            print("Afternoon")
        })

        UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: {
            self.label.text = "Good Evening"
            print("Evening")
        })
        UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
            self.label.text = "Good Night"
            print("Night")
        })

    }, completion: nil)
}

@IBAction func didPressBtn(_ sender: Any) {
    changeText()
}

标签: swiftcakeyframeanimation

解决方案


我不相信在 UIView.animate 中更改 UILabel 的文本是可以直接动画的。

一个可能的解决方案是创建四个不同的 UILabel,并根据需要在它们之间设置动画。

但是,有 3rd 方库可用! https://github.com/lexrus/LTMorphingLabel(通过https://github.com/ameizi/awesome-ios-animation找到)


推荐阅读