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())
Rating Control SwiftUI
Advertisement