はじめに
映画評価や書籍評価など、評価系のアプリは意外と多いはずです。
AppStoreのような星の評価ができるViewを調べると、整数部分を星の数として、実装しているものが多くありました。
しかし、少数部分も反映できるViewはなかったので、考えてみました
サンプルアプリ
実装
struct ReviewView: View {
@Binding var rate: CGFloat
var rootWidth: CGFloat
var body: some View {
ZStack(alignment: .leading) {
HStack {
ForEach(0..<5) { _ in
Image(systemName: "star")
.resizable()
.scaledToFit()
}
}
.frame(width: rootWidth, height: 100)
.foregroundStyle(.gray)
Rectangle()
.foregroundStyle(.yellow)
.frame(width: calcWidth, height: 100)
}
.frame(width: rootWidth)
.mask {
HStack {
ForEach(0..<5) { _ in
Image(systemName: "star.fill")
.resizable()
.scaledToFit()
}
}
}
}
private var calcWidth: CGFloat {
rootWidth * (rate / 5)
}
}
使用側
import SwiftUI
struct ContentView: View {
@State var rate: CGFloat = 0.0
var body: some View {
VStack {
Text("評価: \(rate)").font(.title)
ReviewView(rate: $rate, rootWidth: 350)
Slider(value: $rate, in: 0...5).frame(width: 350)
}
}
}
おわり
一応形にはなっていますが、いいコードとは言えないので、改善案があれば編集リクエストください!