SwiftUI 使用 ProgressViewStyle 自定义 ProgressView

22 min read

SwiftUI 中的 ProgressViewStyle 协议允许我们自定义 ProgressView 的样式。

要自定义 ProgressView,我们需要:

  1. 创建一个遵守 ProgressViewStyle 协议的自定义样式
  2. 在 ProgressView 中应用这个自定义样式

以下是一个示例,展示如何使用 ProgressViewStyle 自定义 ProgressView:

struct MyProgressViewStyle: ProgressViewStyle {
    var color: Color
    
    func makeBody(configuration: Configuration) -> some View {
        VStack {
            Spacer()
            ZStack(alignment: .leading) {
                Rectangle()
                    .foregroundColor(Color.gray.opacity(0.3))
                    .frame(height: 15)
                Rectangle()
                    .foregroundColor(color)
                    .frame(width: CGFloat(configuration.fractionCompleted ?? 0) * UIScreen.main.bounds.size.width, height: 15)
            }
            Spacer()
            Text("\(Int(configuration.fractionCompleted ?? 0 * 100)) %")
                .font(.caption)
        }
    }
}

struct ContentView: View {
    @State var progress: Double = 0.5
    
    var body: some View {
        VStack {
            ProgressView(value: progress, total: 1.0)
                .progressViewStyle(MyProgressViewStyle(color: .blue))
            Button("Update Progress") {
                progress += 0.1
            }
        }
    }
}

在上面的示例中,我们创建了一个名为 MyProgressViewStyle 的自定义样式。它有一个 color 属性来定义进度条的颜色,并使用 VStack、Rectangle 和 Text 来构建自定义的样式。

在 ContentView 中,我们将 ProgressView 应用到了我们的自定义样式。我们还使用一个可交互的按钮来更新 progress 值,以显示自定义进度条。

注意,我们还传递了 value 和 total 属性来定义进度条的当前值和最大值。这两个属性是 ProgressView 中可选的,但如果你传递它们,进度条将会在 UI 上显示百分比。