SwiftUI 如何使用 ProgressView 显示不确定的进度?

10 min read

SwiftUI 中的 ProgressView 可以显示两种类型的进度:确定进度和不确定进度。确定进度是指已知进度的情况,例如上传或下载文件时的百分比进度。而不确定进度是指不知道进度,一般用于表示正在进行中的操作。

要显示不确定的 ProgressView,可以使用 ProgressView 的 init 方法,并将 ProgressViewStyle 设置为 .circular 或 .linear,示例如下:

struct ContentView: View {
    @State var showProgressView = true
    
    var body: some View {
        ZStack {
            // Your content here
            if showProgressView {
                ProgressView()
                    .progressViewStyle(.circular) // or .linear
            }
        }
    }
}

以上代码中,我在 Stack 中嵌套了一个条件语句,只有当 showProgressView 值为 true 时才会显示 ProgressView。当 showProgressView 值为 false 时,则不会显示 ProgressView。

在实际使用中,可以根据需要在操作开始、进行中和结束时,将 showProgressView 值设置为 true 或 false,以显示或隐藏进度条。例如,在发起网络请求时,可以将 showProgressView 值设置为 true,然后当请求成功或失败时,再将其设置为 false,以表示操作已经结束。