gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:08:49 25 4
gpt4 key购买 nike

当用户进入包含下图的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com