如何使用关键帧链接动画
Posted
技术标签:
【中文标题】如何使用关键帧链接动画【英文标题】:How to chain animations using key frames 【发布时间】:2020-11-27 08:29:45 【问题描述】:我希望堆栈视图的排列子视图以级联方式可见,但它们都同时出现:
let i = 5
let animation = UIViewPropertyAnimator(duration: 5, timingParameters: UICubicTimingParameters())
animation.addAnimations
UIView.animateKeyframes(withDuration: 0, delay: 0, options: .calculationModeCubicPaced)
for index in 0..<i
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: Double(1/i))
let label = self.stackView.arrangedSubviews[index]
label.alpha = 1
completion: (_) in
return
animation.startAnimation()
我的期望是,将选项设置为 calculationModePaced
或 calculationModeCubicPaced
会以均匀间隔的方式为每个关键帧设置动画,即使我没有单独设置 withRelativeStartTime
参数(并将它们设置为 0)。
我尝试将选项更改为calculationModeLinear
并手动设置withRelativeStartTime
:
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5)
let label = self.stackView.arrangedSubviews[0]
label.alpha = 1
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5)
let label = self.stackView.arrangedSubviews[1]
label.alpha = 1
但是,标签仍然同时显示。
【问题讨论】:
【参考方案1】:要使其按预期工作,您应该:
-
删除
, options: .calculationModeCubicPaced
修复 relativeDuration - 1.0 / Double(i)
设置相对开始时间 - Double(index) / Double(i)
示例:
let totalCount = labels.count
let labelDuration = 1.0 / Double(totalCount)
let animation = UIViewPropertyAnimator(duration: 5, timingParameters: UICubicTimingParameters())
animation.addAnimations
UIView.animateKeyframes(withDuration: 0, delay: 0, animations: [weak self] in
for i in 0..<totalCount
UIView.addKeyframe(withRelativeStartTime: Double(i) / Double(totalCount), relativeDuration: labelDuration)
self?.labels[i].alpha = 1
)
animation.startAnimation()
【讨论】:
以上是关于如何使用关键帧链接动画的主要内容,如果未能解决你的问题,请参考以下文章