Swift Progress View 动画使栏走得更远超过 100%

Mar*_*røt 1 uiview ios animatewithduration swift

为 ProgressView 使用动画时,如果我让动画用完,它会完全正常,但是如果我在动画仍在运行时再次尝试运行此代码,它将向当前条添加 100% 并使其通过条. 图像应该更合乎逻辑地解释情况。

进度从 1.0 (100%) 开始:

在此处输入图片说明

进展已经进行了一半:

进展已经进行了一半

代码再次运行,导致进度超过 100%,尽管它使用了正确的时间来完成。

代码再次运行,导致进度超过 100%,尽管它使用了正确的时间来完成。

这是使用的代码:

self.progressView.setProgress(1.0, animated: false)
        
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  UIView.animate(withDuration: 10, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { [unowned self] in
    self.progressView.setProgress(0, animated: true)
  })
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

dea*_*eef 9

setProgress(_:animated:)方法已经为您处理动画。当该animated参数设置为 时true,进度变化将会有动画效果。

尝试不使用动画块:

self.progressView.setProgress(1.0, animated: false)

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    self.progressView.setProgress(0.0, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

还要确保这不是自动布局问题。检查进度视图上的约束并确保其宽度受到正确约束。


Don*_*Mag 9

一些快速的研究...

原来UIProgressView需要一些特别的努力来停止当前的动画。看看这是否适合你:

    // stop any current animation
    self.progressView.layer.sublayers?.forEach { $0.removeAllAnimations() }

    // reset progressView to 100%
    self.progressView.setProgress(1.0, animated: false)

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        // set progressView to 0%, with animated set to false
        self.progressView.setProgress(0.0, animated: false)
        // 10-second animation changing from 100% to 0%
        UIView.animate(withDuration: 10, delay: 0, options: [], animations: { [unowned self] in
            self.progressView.layoutIfNeeded()
        })
    }
Run Code Online (Sandbox Code Playgroud)