1

I have var color: String = "blue". With that variable I want to set the background color of a Button. I tried .background(Color(color)), but that doesn't work. .background(Color.blue) or .background(Color(.blue)) work, but I want to use the String variable for it. How to do this?

nils
  • 11
  • 3

1 Answers1

1

You could compare the string which comes in and get the correct color from that. See the following example:

struct ContentView: View {
    
    var body: some View {
        Color(wordName: "red")
    }
}


extension Color {
    
    init?(wordName: String) {
        switch wordName {
        case "clear":       self = .clear
        case "black":       self = .black
        case "white":       self = .white
        case "gray":        self = .gray
        case "red":         self = .red
        case "green":       self = .green
        case "blue":        self = .blue
        case "orange":      self = .orange
        case "yellow":      self = .yellow
        case "pink":        self = .pink
        case "purple":      self = .purple
        case "primary":     self = .primary
        case "secondary":   self = .secondary
        default:            return nil
        }
    }
}
George
  • 25,988
  • 10
  • 79
  • 133
  • I had hoped that this would not be necessary, but thank you – nils Jan 03 '21 at 18:05
  • @nils I hoped it would be easier to do. I just took this code from one of my current projects and changed it to work best for you – George Jan 03 '21 at 18:12