ios - swift 3 : How to animate a view background color similar to a progress bar

标签 ios swift uiview swift3 progress-bar

当用户进入包含下图的 View Controller 时,我希望根据值(在本例中为 70)对蓝色进行动画处理。这意味着,颜色从 View 中的 0px 开始加载,并且停止在任何值的数量上。另外,我希望在加载颜色的同时,数字从 0 计数到最终值。为了实现这一目标,您是否有任何提示/链接或方向可以指导我?提前致谢! enter image description here

最佳答案

使用所需的backgroundColor创建progressView

let progressView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 50))
progressView.backgroundColor = .blue
self.view.addSubview(progressView)

调用以下函数使其宽度与 progress

成比例
func setProgress(_ progress: CGFloat) {
    let fullWidth: CGFloat = 200
    let newWidth = progress/100*fullWidth
    UIView.animate(withDuration: 1.5) {
        self.progressView.frame.size = CGSize(width: newWidth, height: self.progressView.frame.height)
    }
}

创建一个progressLabel 和一个currentProgress 变量

let progressLabel = UILabel(frame: CGRect(x: 0, y: 100, width: 50, height: 50))
var currentProgress: CGFloat = 0
label.text = String(currentProgress)
self.view.addSubview(progressLabel)

调用以下函数以延迟循环更新其进度,示例:setLabelProgress(initialValue: self.currentProgress, targetValue: 70)

func setLabelProgress(initialValue: CGFloat, targetValue: CGFloat) {

    guard currentProgress != targetValue else { return }

    let range = targetValue - initialValue
    let increment = range/CGFloat(abs(range))
    let duration: TimeInterval = 1.5
    let delay = duration/TimeInterval(range)
    currentProgress += increment
    progressLabel.text = String(describing: currentProgress)

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) {
        self.setLabelProgress(initialValue: initialValue, targetValue: targetValue)
    }
}

对于第二个标签调用相同的函数,但交换 initialValuetargetValue

关于ios - swift 3 : How to animate a view background color similar to a progress bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337427/

相关文章:

ios - 如何为 iPhone 8 屏幕与 iPhone X 及更高版本的底部 anchor 设置不同的常量?

swift - 警告 : CoreAnimation stiffness must be greater than 0, 但我使用 viewAnimation

swift - 如何动态添加自定义 View xib文件

ios - 单例函数 IOS

ios - 在其他与网络服务一起使用的 swift 文件中调用函数不返回任何内容

ios - 使用动画滚动 textView 的底部

Swift 将 CABasicAnimation 与 label.text 同步

ios - iOS 中的形状动画

ios - Swift self.performSegueWithIdentifier 随机不起作用

swift - 使用通知中心将值设置为 TableView 中的标签