SwiftUI自定义一个水平渐变进度条
文章目录
- 一、前言
- 二、核心代码
一、前言
系统自带的ProgressView只能改下进度条颜色,别的做不了,这里演示下自定义进度条如何做

二、核心代码
import SwiftUIstruct ProgressContent: View {@State private var isActive: Bool = false@State private var progress: Double = 0.0var body: some View {VStack {Button("到80"){isActive.toggle()withAnimation(.easeInOut(duration: 2)) {progress = 80}}Button("到100"){isActive.toggle()withAnimation(.easeInOut(duration: 2)) {progress = 100}}
// ProgressView("Downloading...", value: 50, total: 100)// 移除文字,修改颜色ProgressView(value: progress, total: 100).progressViewStyle(GradientProgressViewStyle())
// Color.clear.animatedProgress(progress)}}
}// MARK: - ✅ 渐变 ProgressView 样式(去掉内部 animation)
struct GradientProgressViewStyle: ProgressViewStyle {func makeBody(configuration: Configuration) -> some View {let fraction = configuration.fractionCompleted ?? 0return VStack(alignment: .leading, spacing: 8) {GeometryReader { geometry inZStack(alignment: .leading) {// 背景Rectangle().fill(Color.gray.opacity(0.3)).frame(height: 8).cornerRadius(4)// 前景渐变Rectangle().fill(LinearGradient(colors: [.purple, .blue, .cyan],startPoint: .leading,endPoint: .trailing)).frame(width: geometry.size.width * fraction, height: 8).cornerRadius(4)}}.frame(height: 8)}}
}
#Preview {ProgressContent()
}