82 lines
1.6 KiB
Swift
82 lines
1.6 KiB
Swift
|
//
|
||
|
// StarRating.swift
|
||
|
// ReviewsUIKit
|
||
|
//
|
||
|
// Created by Javier Cicchelli on 19/03/2024.
|
||
|
// Copyright © 2024 Röck+Cöde. All rights reserved.
|
||
|
//
|
||
|
|
||
|
import SwiftUI
|
||
|
|
||
|
public struct StarRating: View {
|
||
|
|
||
|
// MARK: Constants
|
||
|
private let rating: Int
|
||
|
private let total: Int
|
||
|
|
||
|
// MARK: Initialisers
|
||
|
public init(
|
||
|
_ rating: Int,
|
||
|
of total: Int
|
||
|
) {
|
||
|
self.rating = rating
|
||
|
self.total = total
|
||
|
}
|
||
|
|
||
|
// MARK: Body
|
||
|
public var body: some View {
|
||
|
HStack {
|
||
|
ForEach(
|
||
|
1...total,
|
||
|
id: \.self
|
||
|
) { index in
|
||
|
if #available(iOS 15.0, *) {
|
||
|
Image.Icon.star
|
||
|
.symbolVariant(symbolVariant(for: index))
|
||
|
} else {
|
||
|
image(for: index)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
// MARK: - Helpers
|
||
|
private extension StarRating {
|
||
|
|
||
|
// MARK: Functions
|
||
|
func image(for index: Int) -> Image {
|
||
|
index <= rating
|
||
|
? .Icon.starFill
|
||
|
: .Icon.star
|
||
|
}
|
||
|
|
||
|
@available(iOS 15.0, *)
|
||
|
func symbolVariant(for index: Int) -> SymbolVariants {
|
||
|
index <= rating
|
||
|
? .fill
|
||
|
: .none
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
// MARK: - Image+Constants
|
||
|
private extension Image {
|
||
|
enum Icon {
|
||
|
static let star: Image = .init(systemName: "star")
|
||
|
static let starFill: Image = .init(systemName: "star.fill")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// MARK: - Previews
|
||
|
#Preview("Star Rating") {
|
||
|
VStack(spacing: 8) {
|
||
|
StarRating(1, of: 5)
|
||
|
StarRating(2, of: 5)
|
||
|
StarRating(3, of: 5)
|
||
|
StarRating(4, of: 5)
|
||
|
StarRating(5, of: 5)
|
||
|
}
|
||
|
}
|