【问题标题】:How to control the speed of UIView animation?如何控制 UIView 动画的速度?
【发布时间】:2017-10-23 10:56:48
【问题描述】:

我正在实现这样的旋转数字视图: https://github.com/jonathantribouharet/JTNumberScrollAnimatedView

但是,我希望动画继续滚动(从 1 到 9,然后回到 1 到 9),而不是从 1 到 9 滚动,直到我手动停止它。

我通过添加垂直堆叠的 UILabel 子视图 1-9 来实现这一点,并在底部为数字 1 添加一个额外的标签。当旋转到底部时(显示底部标签1),在动画完成闭包中,我将变换设置回原点,显示顶部标签1,然后重新开始旋转动画。

这很好用,但由于每次旋转 (1-9-1) 都是独立的,因此 1-9 的动画会先加速,然后在 1 处停止,并在下一次迭代时加快速度。这不是我想要的,我希望旋转在迭代之间保持恒定的速度。

如何使用 UIView 动画做到这一点?

代码如下:

 public func startAnimation(){
    UIView.setAnimationCurve(UIViewAnimationCurve.easeIn)
    UIView.animate(withDuration: TimeInterval(self.loopDuration), animations: { [unowned self] in
        self.container!.transform = CGAffineTransform(translationX: 0, y: CGFloat(-(self.endNumber-self.startNumber+1)*(self.size)))
    }) { [unowned self] (completed) in
        if self.isAnimationStopped {
            self.container!.transform = CGAffineTransform(translationX: 0, y: 0)
            UIView.setAnimationCurve(UIViewAnimationCurve.easeOut)
            UIView.animate(withDuration: TimeInterval(self.loopDuration), animations: {
                self.container!.transform = CGAffineTransform(translationX: 0, y: CGFloat(-self.targetY))
            })
        } else {
            self.container!.transform = CGAffineTransform(translationX: 0, y: 0)
            self.startAnimation()
        }
    }

}

【问题讨论】:

    标签: ios swift animation uiview


    【解决方案1】:

    默认情况下,UIView 动画使用ease-in, ease-out 动画计时,动画平稳加速,运行,然后减速停止。

    您需要使用较长形式的 UIView.animate,animate(withDuration:delay:options:animations:completion:),它带有选项参数,并指定时间曲线.curveLinear

    只需为延迟指定 0.0 和 options: .curveLinear

    编辑:

    请注意,如果您需要指定多个选项,例如 .curveLinear.allowUserInteraction,您将使用 OptionSet 语法,例如 options: [.curveLinear, .allowUserInteraction]

    【讨论】:

    • 就像一个魅力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多