Last active
April 13, 2023 11:59
-
-
Save ayaysir/2d2cc0df1e0a4282382b96ea286fc506 to your computer and use it in GitHub Desktop.
SwiftUI: Linear Progress View with gradation - https://itnext.io/how-to-create-a-custom-progressview-with-swiftui-e1edb443a68e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct GradientProgressStyle<Stroke: ShapeStyle, Background: ShapeStyle>: ProgressViewStyle { | |
var stroke: Stroke | |
var fill: Background | |
var caption: String = "" | |
var cornerRadius: CGFloat = 10 | |
var height: CGFloat = 20 | |
var animation: Animation = .easeInOut | |
func makeBody(configuration: Configuration) -> some View { | |
let fractionCompleted = configuration.fractionCompleted ?? 0 | |
return VStack { | |
ZStack(alignment: .topLeading) { | |
GeometryReader { geo in | |
Rectangle() | |
.fill(fill) | |
.frame(maxWidth: geo.size.width * CGFloat(fractionCompleted)) | |
.animation(animation) | |
} | |
} | |
.frame(height: height) | |
.cornerRadius(cornerRadius) | |
.overlay( | |
RoundedRectangle(cornerRadius: cornerRadius) | |
.stroke(stroke, lineWidth: 2) | |
) | |
if !caption.isEmpty { | |
Text("\(caption)") | |
.font(.caption) | |
} | |
} | |
} | |
} | |
struct ContentView: View { | |
@State private var gradient = LinearGradient( | |
gradient: Gradient(colors: [.green, .blue]), | |
startPoint: .top, | |
endPoint: .bottom | |
) | |
@State var progress: Double = 40.0 | |
var body: some View { | |
let gradientStyle = GradientProgressStyle( | |
stroke: gradient, | |
fill: gradient, | |
caption: "Some fancy caption" | |
) | |
VStack { | |
Image(systemName: "globe") | |
.imageScale(.large) | |
.foregroundColor(.accentColor) | |
Text("Hello, world!") | |
ProgressView(value: progress, total: 100) | |
.progressViewStyle(gradientStyle) | |
.foregroundStyle(LinearGradient(gradient: Gradient(colors: [.white, .black]), startPoint: .top, endPoint: .bottom)) | |
Button { | |
progress += 10.0 | |
} label: { | |
Text("plus") | |
} | |
Button { | |
progress = 0 | |
} label: { | |
Text("Reset") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment