我有一个进度条,我写了这样的.

ZStack(alignment: .leading) {
                RoundedRectangle(cornerRadius: 20)
                    .foregroundColor(.gray)
                    .frame(width: 300, height: 20, alignment: .center)
                RoundedRectangle(cornerRadius: 20)
                    .foregroundColor(Color(red: min(2.0 - (fraction * 2.0), 1.0), green: min((fraction * 2.0), 1.0), blue: 0))
                    .frame(width: 300 * fraction, height: 20)
                    
            }

进度用可变分数中的小数表示.

Here is an example of this code with fraction set to increasing amounts: progress bar

当第一次加载视图时,我希望所有的条从分数=0和红色开始,并在一秒钟内快速扩展和着色到所需的分数.

我的问题是,我还没有弄清楚如何设置变量值的动画,以及如何在修改器中使用它.这是在重新绘制视图时发生的.

这样比较理想(尽管这段代码显然无法编译):


                RoundedRectangle(cornerRadius: 20)
                    .foregroundColor(Color(red: min(2.0 - ((fraction*frame) * 2.0), 1.0), green: min(((fraction*frame) * 2.0), 1.0), blue: 0))
                    .frame(width: 300 * (fraction*frame), height: 20)
                    .animate(start: frame = 0; increment: frame += 0.1; end: frame <= 1, duration: 1s)

推荐答案

可以将每个进度视图与跟踪更改值的自己的进度状态分开.

使用Xcode 13.4/iOS 15.5测试

demo

主要部分:

        ZStack(alignment: .leading) {
            RoundedRectangle(cornerRadius: 20)
                .foregroundColor(.gray)
                .frame(width: 300, height: 20, alignment: .center)
            RoundedRectangle(cornerRadius: 20)
                .foregroundColor(Color(red: min(2.0 - (fraction * 2.0), 1.0), green: min((fraction * 2.0), 1.0), blue: 0))
                .frame(width: 300 * fraction, height: 20)
        }
        .animation(.easeInOut(duration: 1.0), value: fraction)
        .onAppear {
            fraction = currentProgress
        }
        .onChange(of: currentProgress) {
            fraction = $0
        }

Test module on GitHub

Ios相关问答推荐

带外部笔划的圆形进度视图

在Android和iOS上从后台恢复应用程序后,inappwebview上出现白屏?

Swift在SceneKit中为scnnode添加自定义几何体(视图)

封装 Swift 导入

如何将 Info.plist 文件添加到 Xcode for admob,错误 添加后会产生多个命令

查找东南亚语言(泰语、高棉语、老挝语、缅甸语)中的单词边界

使用 SwiftUI 显示多个 VNRecognizedObjectObservation 边界框时偏移量错误

var name: String 时 print(nil) 和 print(name) 的区别? = 无

iOS 16 中的状态栏 colored颜色

Task.cancel() 的 TaskPriority 的区别

SwiftUI 切换语句

TextField 重复输入 SwiftUI

从父母到子元素的 Swift Pass 事件

如何将私钥添加到分发证书?

iOS 8 - 使用自定义演示关闭视图控制器后屏幕空白

每次运行后,Xcode 6 都会在 iOS8 模拟器中重命名我的应用程序目录.

直接下载Xcode模拟器

如何使用 presentModalViewController 创建透明视图

我的应用程序因使用广告支持框架而被拒绝.哪个图书馆负责?

在两个或多个 iPhone 应用程序之间共享数据