Skip to content

Instantly share code, notes, and snippets.

@wildthink
Last active September 12, 2021 07:43
Show Gist options
  • Save wildthink/d4b785dc26da51b9dc249008312441d3 to your computer and use it in GitHub Desktop.
Save wildthink/d4b785dc26da51b9dc249008312441d3 to your computer and use it in GitHub Desktop.
//
// RatingsView.swift
// RatingsView
//
// Created by Jason Jobe on 9/12/21.
//
import SwiftUI
public struct RatingsView: View {
var rating: CGFloat
var maxRating: Int
var symbol: String
var color: Color
var backgroundColor: Color
public init(_ rating: CGFloat, of max: Int, symbol: String = "star.fill",
color: Color = .yellow, backgroundColor: Color = .white) {
self.rating = rating
self.maxRating = max
self.symbol = symbol
self.color = color
self.backgroundColor = backgroundColor
}
public var body: some View {
let stars = HStack(spacing: 8) {
ForEach(0..<maxRating) { _ in
Image(systemName: symbol)
.resizable()
.aspectRatio(contentMode: .fit)
.shadow(radius: 1)
}
}
stars.overlay(
GeometryReader { g in
let width = rating / CGFloat(maxRating) * g.size.width
ZStack(alignment: .leading) {
Rectangle()
.frame(width: width)
.foregroundColor(color)
}
}
.mask(stars)
)
.foregroundColor(backgroundColor)
}
}
struct RatingsView_Previews: PreviewProvider {
static var previews: some View {
RatingsView(3.5, of: 5)
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment