From 2313afb8c41c00b096bc2c229c7379a97295e7f3 Mon Sep 17 00:00:00 2001 From: Javier Cicchelli Date: Wed, 20 Mar 2024 00:48:27 +0100 Subject: [PATCH] Implemented the StarRating component in the UI library. --- .../Kit/Sources/Components/StarRating.swift | 81 +++++++++++++++++++ .../HostingConfiguration.swift | 0 2 files changed, 81 insertions(+) create mode 100644 Libraries/UI/Kit/Sources/Components/StarRating.swift rename Libraries/UI/Kit/Sources/{Components => Configurations}/HostingConfiguration.swift (100%) diff --git a/Libraries/UI/Kit/Sources/Components/StarRating.swift b/Libraries/UI/Kit/Sources/Components/StarRating.swift new file mode 100644 index 0000000..1c3b8e8 --- /dev/null +++ b/Libraries/UI/Kit/Sources/Components/StarRating.swift @@ -0,0 +1,81 @@ +// +// StarRating.swift +// Feed +// +// 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) + } +} diff --git a/Libraries/UI/Kit/Sources/Components/HostingConfiguration.swift b/Libraries/UI/Kit/Sources/Configurations/HostingConfiguration.swift similarity index 100% rename from Libraries/UI/Kit/Sources/Components/HostingConfiguration.swift rename to Libraries/UI/Kit/Sources/Configurations/HostingConfiguration.swift