ProgressView 进度条

显示模糊进度

ProgressView 可以在不附加任何类型的绑定的情况下创建,这将导致它们永远显示一个旋转的动画,而不是显示某种明显的进度。

struct ContentView: View {
var body:some View {
        ProgressView("Downloading…")
    }
}

显示准确进度

ProgressView 可以绑定到 Double 类型的属性,以显示水平进度条。

// 例如,这将创建一个标题为“Downloading”的进度条,该进度条将读取 downloadAmount 以确定进度条应有多满:
struct ContentView: View {
    @State private var downloadAmount = 0.0
    var body: some View {
        VStack {
            ProgressView("Downloading…", value: downloadAmount, total: 100)
        }
    }
}

// 在实践中为了检查进度条是否正常工作,您需要某种方法来实际更改该值,例如计时器、网络请求或其他用户界面
struct ContentView: View {
    @State private var downloadAmount = 0.0
    let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
    var body: some View {
        ProgressView("Downloading…", value: downloadAmount, total: 100)
            .onReceive(timer) { _ in
                if downloadAmount < 100 {
                    downloadAmount += 2
                }
            }
    }
}

注意:如果您将进度值设置为高于进度 total 参数 ,Xcode 会生气,请确保设置正确的上限。


使用 ProgressViewStyle 自定义

SwiftUI 提供了 ProgressViewStyle 协议,来为 ProgressView 创建自定义设计,具体步骤如下:

以下有一个自定义样式,它创建一个仪表,将进度显示为一个描边圆圈,随着进度的增加而完成:

struct GaugeProgressStyle: ProgressViewStyle {
    var strokeColor = Color.blue
    var strokeWidth = 25.0

    func makeBody(configuration: Configuration) -> some View {
        let fractionCompleted = configuration.fractionCompleted ?? 0
        return ZStack {
            Circle()
                .trim(from: 0, to: fractionCompleted)
                .stroke(strokeColor, style: StrokeStyle(lineWidth: strokeWidth, lineCap: .round))
                // 自定义样式如何将圆圈逆时针旋转 90 度,因此圆圈从顶部开始绘制进度
                .rotationEffect(.degrees(-90))
        }
    }
}

// A view letting you adjust the progress with tap gestures
struct ContentView: View {
    @State private var progress = 0.2
    var body: some View {
        ProgressView(value: progress, total: 1.0)
            .progressViewStyle(GaugeProgressStyle())
            .frame(width: 200, height: 200)
            .contentShape(Rectangle())
            .onTapGesture {
                if progress < 1.0 {
                    withAnimation {
                        progress += 0.2
                    }
                }
            }
    }