0

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

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

我的期望是,即使我没有单独设置参数(并将它们设置为 0),也可以以均匀间隔的方式为每个关键帧设置选项calculationModePaced或为其设置动画。calculationModeCubicPacedwithRelativeStartTime

我尝试将选项更改为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
}

但是,标签仍然同时出现。

4

1 回答 1

1

要使其按预期工作,您应该:

  1. 消除, options: .calculationModeCubicPaced
  2. 修复 relativeDuration -1.0 / Double(i)
  3. 使用RelativeStartTime 设置 -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()
于 2020-11-27T12:07:38.893 回答