Skip to content

Instantly share code, notes, and snippets.

@michaelswarm
Created July 19, 2020 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelswarm/900ad8289b4c4bb14b2e20cf6db7f452 to your computer and use it in GitHub Desktop.
Save michaelswarm/900ad8289b4c4bb14b2e20cf6db7f452 to your computer and use it in GitHub Desktop.
Rating Control SwiftUI
import SwiftUI
import PlaygroundSupport
// Rating Control
// From: https://www.hackingwithswift.com/books/ios-swiftui/adding-a-custom-star-rating-component
// Uses images with tap gesture, not button. (Is image with tap gesture a basic button?)
struct RatingControl: View {
var maxRating = 5
@State var rating = 0
// Image(systemName:) uses SF Symbols.
var offImage = Image(systemName: "star")
var onImage = Image(systemName: "star.fill")
func image(for number: Int) -> Image {
if number > rating {
return offImage ?? onImage
} else {
return onImage
}
}
var body: some View {
VStack {
Text("Rating Control")
HStack {
ForEach(1..<maxRating + 1) { number in
self.image(for: number)
//.foregroundColor(number > self.rating ? self.offColor : self.onColor)
.onTapGesture { self.rating = number }
}
}
}
}
}
PlaygroundPage.current.setLiveView(RatingControl())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment