[Swift] 69 watchOS用ColorPicker作成

[Mac M2 Pro 12CPU, Ventura 13.6.1, iOS 17.2.1, Xcode 15.2]

久々の投稿です。

watchOS用に25色ColorPickerを作成しました。

import SwiftUI

struct ColorPickerAW: View {
    @Binding var selectedColor: Color
    var onColorSelected: (() -> Void)?

    // カラーコードをColorに変換する関数
    func colorFromHex(_ hex: String) -> Color {
        var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
        hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
        
        var rgb: UInt64 = 0
        
        Scanner(string: hexSanitized).scanHexInt64(&rgb)
        
        let red = Double((rgb & 0xFF0000) >> 16) / 255.0
        let green = Double((rgb & 0x00FF00) >> 8) / 255.0
        let blue = Double(rgb & 0x0000FF) / 255.0
        
        return Color(red: red, green: green, blue: blue)
    }
    
    // カラーコードの配列
    let colors: [String] = [
        "#FFFFFF", "#C0C0C0", "#808080", "#000000", "#000080",
        "#0000FF", "#00FFFF", "#40E0D0", "#008080", "#808000",
        "#008000", "#00FF00", "#F5F5DC", "#FFFF00", "#FFD700",
        "#FFA500", "#FF7F50", "#FF0000", "#800000", "#A52A2A",
        "#DDA0DD", "#E6E6FA", "#FFC0CB", "#FF00FF", "#800080"
    ]
    
    var body: some View {
        // グリッド表示
        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 5), spacing: 10) {
            ForEach(colors, id: \.self) { colorCode in
                Rectangle()
                    .fill(colorFromHex(colorCode))
                    .frame(width: 25, height: 25) // 長方形のサイズ
                    .onTapGesture {
                        // タップされた色を選択
                        self.selectedColor = colorFromHex(colorCode)
                        // 親ビューに通知
                        self.onColorSelected?()
                    }
            }
        }
        .padding()
    }
}
VStack(){
    Toggle("Show_Era".localized, isOn: $eraName)
        .frame(width: 140, height: 80, alignment: .center)
        .foregroundColor(.blue)
        .font(.system(size: 24))
        .onChange(of: eraName) { newValue in
            UserDefaults.standard.set(newValue, forKey: eraNameKey)
            print("eraNameが\(newValue)に変更され、UserDefaultsに保存されました。")
        }
    HStack(spacing:2){
        Text("Watch\nRow1")
        Rectangle()
            .fill(colorWatch1)
            .frame(width: 30, height: 30)
            .opacity(1.0)
        Button("Set") {
            showingColorPicker = true
        }
    }
    
    Spacer()
}
.sheet(isPresented: $showingColorPicker) {
    ColorPickerAW(selectedColor: $selectedColor) {
        showingColorPicker = false
        colorWatch1 = selectedColor
    }
}