Change background color of a view depending on 3 possibilities of variable

Viewed 47

Is it possible to switch background color depending on bool variable.

@State var isOpen: Bool = true

.background(isOpen ? .white: .black)

My question is: Is it possible to switch between 3 colors depending 3 states? Bool only has 2. Maybe using string or int value??

@State var category: String = "car" or @State var category: Int = 1

How do we say choose between 3 colors??

.background(????????)

2 Answers

If you have more than 2 cases, it is better to create a function or a computed property to determine your color. Here is a standalone example that uses an .enum for the Category and switches randomly between the categories:

struct ContentView: View {
    enum Category: String, CaseIterable {
        case car, boat, house, plane
    }
    
    @State private var category = Category.car
    
    var body: some View {
        ZStack {
            Button(category.rawValue) {
                category = Category.allCases.randomElement()!
            }
            .padding(20)
            .foregroundColor(.white)
            .background(.black)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(chooseColor(category: category))
    }
    
    func chooseColor(category: Category) -> Color {
        switch category {
        case .car: return .red
        case .boat: return .blue
        case .house: return .yellow
        case .plane: return .white
        }
    }
}

you could try this, when status==0 -> red, status==1 -> blue, otherwise green:

   @State var status = 0

   .background(status == 0 ? .red : (status == 1 ? .blue : .green))

Here is an example code on how to use it:

struct ContentView: View {
    @State var status = 0
    
    var body: some View {
        ZStack {
            Color(status == 0 ? .red : (status == 1 ? .blue : .green))
            Picker("Color", selection: $status) {
                ForEach(0..<3, id: \.self) { i in
                    Text("\(i)").tag(i)
                }
            }.pickerStyle(.segmented)
        }
        Text("Color Color Color")
            .background(status == 0 ? .red : (status == 1 ? .blue : .green))
    }
}
Related