|
| 1 | +import SwiftUI |
| 2 | + |
| 3 | +struct CircularProgressView: View { |
| 4 | + let value: Float? |
| 5 | + |
| 6 | + var strokeWidth: CGFloat = 4 |
| 7 | + var diameter: CGFloat = 22 |
| 8 | + var primaryColor: Color = .secondary |
| 9 | + var backgroundColor: Color = .secondary.opacity(0.3) |
| 10 | + |
| 11 | + @State private var rotation = 0.0 |
| 12 | + @State private var trimAmount: CGFloat = 0.15 |
| 13 | + |
| 14 | + var autoCompleteThreshold: Float? |
| 15 | + var autoCompleteDuration: TimeInterval? |
| 16 | + |
| 17 | + var body: some View { |
| 18 | + ZStack { |
| 19 | + // Background circle |
| 20 | + Circle() |
| 21 | + .stroke(backgroundColor, style: StrokeStyle(lineWidth: strokeWidth, lineCap: .round)) |
| 22 | + .frame(width: diameter, height: diameter) |
| 23 | + Group { |
| 24 | + if let value { |
| 25 | + // Determinate gauge |
| 26 | + Circle() |
| 27 | + .trim(from: 0, to: CGFloat(displayValue(for: value))) |
| 28 | + .stroke(primaryColor, style: StrokeStyle(lineWidth: strokeWidth, lineCap: .round)) |
| 29 | + .frame(width: diameter, height: diameter) |
| 30 | + .rotationEffect(.degrees(-90)) |
| 31 | + .animation(autoCompleteAnimation(for: value), value: value) |
| 32 | + } else { |
| 33 | + // Indeterminate gauge |
| 34 | + Circle() |
| 35 | + .trim(from: 0, to: trimAmount) |
| 36 | + .stroke(primaryColor, style: StrokeStyle(lineWidth: strokeWidth, lineCap: .round)) |
| 37 | + .frame(width: diameter, height: diameter) |
| 38 | + .rotationEffect(.degrees(rotation)) |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + .frame(width: diameter + strokeWidth * 2, height: diameter + strokeWidth * 2) |
| 43 | + .onAppear { |
| 44 | + if value == nil { |
| 45 | + withAnimation(.linear(duration: 0.8).repeatForever(autoreverses: false)) { |
| 46 | + rotation = 360 |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private func displayValue(for value: Float) -> Float { |
| 53 | + if let threshold = autoCompleteThreshold, |
| 54 | + value >= threshold, value < 1.0 |
| 55 | + { |
| 56 | + return 1.0 |
| 57 | + } |
| 58 | + return value |
| 59 | + } |
| 60 | + |
| 61 | + private func autoCompleteAnimation(for value: Float) -> Animation? { |
| 62 | + guard let threshold = autoCompleteThreshold, |
| 63 | + let duration = autoCompleteDuration, |
| 64 | + value >= threshold, value < 1.0 |
| 65 | + else { |
| 66 | + return .default |
| 67 | + } |
| 68 | + |
| 69 | + return .easeOut(duration: duration) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +extension CircularProgressView { |
| 74 | + func autoComplete(threshold: Float, duration: TimeInterval) -> CircularProgressView { |
| 75 | + var view = self |
| 76 | + view.autoCompleteThreshold = threshold |
| 77 | + view.autoCompleteDuration = duration |
| 78 | + return view |
| 79 | + } |
| 80 | +} |
0 commit comments