Skip to content

Instantly share code, notes, and snippets.

@scottmatthewman
Created April 27, 2020 12:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottmatthewman/7e58671348a1aa387f8526f84a253820 to your computer and use it in GitHub Desktop.
Save scottmatthewman/7e58671348a1aa387f8526f84a253820 to your computer and use it in GitHub Desktop.
Building a custom progress view in SwiftUI
/// This code is designed to be copied and pasted into a Swift Playground.
/// It will work in Xcode (macOS only) or Swift Playgrounds (on iPad or macOS).
import SwiftUI
import PlaygroundSupport
struct SegmentedProgressView: View {
var value: Int
var maximum: Int = 7
var height: CGFloat = 10
var spacing: CGFloat = 2
var selectedColor: Color = .accentColor
var unselectedColor: Color = Color.secondary.opacity(0.3)
var body: some View {
HStack(spacing: spacing) {
ForEach(0 ..< maximum) { index in
Rectangle()
.foregroundColor(index < self.value ? self.selectedColor : self.unselectedColor)
}
}
.frame(maxHeight: height)
.clipShape(Capsule())
}
}
struct ExampleOfProgress: View {
@State var value = 0
var maximum = 10
var body: some View {
VStack(alignment: .leading) {
Text("SegmentedProgressView example")
.font(.headline)
Text("Current value is \(value) out of \(maximum)")
.font(.body)
SegmentedProgressView(value: value, maximum: maximum)
.animation(.default)
.padding(.vertical)
Button(action: {
self.value = (self.value + 1) % (self.maximum + 1)
}) {
Text("Increment value")
}
}
.padding()
}
}
PlaygroundPage.current.liveView = UIHostingController(rootView: ExampleOfProgress())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment