Skip to content

Instantly share code, notes, and snippets.

@dropski
Created July 3, 2023 19:48
Show Gist options
  • Save dropski/6049296cd5506080992e3f84291ced6f to your computer and use it in GitHub Desktop.
Save dropski/6049296cd5506080992e3f84291ced6f to your computer and use it in GitHub Desktop.
SwiftUI Simple Partial Rating
struct ContentView: View {
@State private var sliderValue: Double = 0.0
@State private var selectedIndex: Int = -1
@State private var remainder: Double = 0.0
var body: some View {
VStack {
HStack {
ForEach(0..<5) { index in
ZStack {
Image(systemName: "star.fill")
.transition(.opacity)
.foregroundColor(.gray)
.overlay {
if selectedIndex > index {
GeometryReader { geometry in
Rectangle()
.foregroundColor(.yellow)
.frame(width: geometry.size.width, height: geometry.size.height)
}
.mask {
Image(systemName: "star.fill")
}
} else if Double(index) <= Double(selectedIndex) + remainder {
GeometryReader { geometry in
Rectangle()
.foregroundColor(.yellow)
.frame(width: geometry.size.width * remainder, height: geometry.size.height)
}
.mask {
Image(systemName: "star.fill")
}
}
}
}
}
}
Slider(value: $sliderValue, in: 0.0...5.0)
.padding()
}
.foregroundColor(.white)
.frame(width: 200, height: 300)
.onChange(of: sliderValue) { value in
let newValue = Int(floor(value))
remainder = value.truncatingRemainder(dividingBy: 1)
guard newValue != selectedIndex else {
return
}
selectedIndex = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment