SwiftUI アプリにColor(バックグランド)指定、背景変更

色指定セット

import SwiftUI

final class ColorData: ObservableObject {
    @Published var backgroundColor: Int = 0
    static let SETTINGCOLOR: [(Color, Color, String)] = [(.white, .black, "Default"),
                                                         (.blue, .blue, "Blue"),
                                                         (.brown, .brown, "Brown"),
                                                         (.cyan, .cyan, "Cyan"),
                                                         (.gray, .gray, "Gray"),
                                                         (.green, .green, "Green"),
                                                         (.indigo, .indigo, "Indigo"),
                                                         (.mint, .mint, "Mint"),
                                                         (.orange, .orange, "Orange"),
                                                         (.pink, .pink, "Pink"),
                                                         (.purple, .purple, "Purple"),
                                                         (.red, .red , "Red"),
                                                         (.teal, .teal, "Teal"),
                                                         (.yellow, .yellow, "Yellow")]
    
    func toColor(selct: Int) -> Color {
        UITraitCollection.current.userInterfaceStyle == .light ? Music.SETTINGCOLOR[selct].0 : Music.SETTINGCOLOR[selct].1
    }
    
    func toColorTitle(selct: Int) -> String {
        Music.SETTINGCOLOR[selct].2
    }
}

設定画面色制定

struct AplSettingView: View {
    @EnvironmentObject var colordata: ColorData

    var body: some View {
        Section(header: Label("Application", systemImage: "app")) {
            Picker(selection: self.$colordata.backgroundColor, content: {
                ForEach(0..< ColorData.SETTINGCOLOR.count, id: \.self) { index in
                    HStack {
                        Image(systemName: "paintpalette.fill")
                            .foregroundColor(self.colordata.toColor(selct: index))
                        Text(NSLocalizedString(self.colordata.toColorTitle(selct: index), comment: ""))
                    }
                    .tag(index)
                }
            }, label: {
                Text("Background Color")
            })
                .onChange(of: self.colordata.backgroundColor) {newValue in
                    self.colordata.save()
                }
        }
    }
}

アプリ背景色指定

import SwiftUI

struct ExampleView: View {
    @EnvironmentObject var colordata: ColorData

    var body: some View {
        ZStack {
            self.colordata.toColor(selct: self. colordata.backgroundColor)
                .ignoresSafeArea()
            :
            :
        }
    }
}

SwiftSwift,SwiftUI

Posted by shi-n