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?

4
  • 1
    To create a color from a string you need to have added that color to your assets catalog Commented Jan 3, 2021 at 17:22
  • If you want to store colors as strings, a hex code works pretty well Commented Jan 3, 2021 at 19:41
  • 1
    I'm curious why you want to do this. Are you porting code from another language? Commented Jan 3, 2021 at 21:01
  • @PietroRea I have a .json file with colors stored by their name Commented Jan 5, 2021 at 13:08

1 Answer 1

3

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I had hoped that this would not be necessary, but thank you
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.