动画关键帧针对 UILabel 的值进行动画处理



我运行了下面的代码,标签被完美地移动了。但我想在每次移动的同时增加标签的价值。我试了很多方法,但都不管用。

UIView.animateKeyframes(withDuration: 6, delay: 0, options: [], animations: {

UIView.addKeyframe(withRelativeStartTime: (0 / 6), relativeDuration: (2 / 6), animations: {
self.label.transform = label.transform.translatedBy(x: 0, y: 50) //OK
//I want the value of the label to be increased from 0 to 5 (exactly equal to the duration of this key frame)
})

UIView.addKeyframe(withRelativeStartTime: (2 / 6), relativeDuration: (2 / 6), animations: {
self.label.transform = label.transform.translatedBy(x: 50, y: 0) //OK
//Then I want the value of the label to decrease from 5 to 0
})
}, completion: nil)

你能帮我吗?提前感谢!

你不能在动画块中这样做,你可以使用Timer并改变标签的文本属性。

例如,在你的情况下,我会这样做:

var tick = 0
let duration: TimeInterval = 6
let countTo = 5
Timer.scheduledTimer(withTimeInterval: duration / (2 * Double(countTo)), repeats: true) { timer in
tick += 1
let mod = tick % countTo
if tick >= countTo, tick < countTo * 2 {
label.text = String(countTo - mod)
} else {
label.text = String(mod)
}

if tick >= countTo * 2 {
timer.invalidate()
}
}

UIView.animateKeyframes(withDuration: duration, delay: 0, options: [], animations: {

UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: {
label.transform = label.transform.translatedBy(x: 0, y: 50)
})

UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: {
label.transform = label.transform.translatedBy(x: 50, y: 0)
})
}, completion: nil)

这样你就可以设置你需要的持续时间和你想要计数的数字,并在持续时间内返回0。

相关内容

  • 没有找到相关文章

最新更新