2
2

【SwiftUI】星の数で評価できるViewを作成する

Posted at

はじめに

映画評価や書籍評価など、評価系のアプリは意外と多いはずです。
AppStoreのような星の評価ができるViewを調べると、整数部分を星の数として、実装しているものが多くありました。

しかし、少数部分も反映できるViewはなかったので、考えてみました

サンプルアプリ

Simulator Screen Recording - iPhone 15 Pro - 2024-02-12 at 18.37.14.gif

実装

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)
        }
    }
}

おわり

一応形にはなっていますが、いいコードとは言えないので、改善案があれば編集リクエストください!

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2