如何使用关键帧链接动画

How to chain animations using key frames

我希望堆栈视图的排列子视图以级联方式可见,但它们同时出现:

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()

我的期望是,即使我没有单独设置 withRelativeStartTime 参数,将选项设置为 calculationModePacedcalculationModeCubicPaced 也会以均匀间隔的方式为每个关键帧设置动画(并将它们设为 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
  2. 修复相对持续时间 - 1.0 / Double(i)
  3. 设置相对开始时间 - 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()