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?
            Asked
            
        
        
            Active
            
        
            Viewed 1,184 times
        
    1
            
            
         
    
    
        nils
        
- 11
- 3
- 
                    1To create a color from a string you need to have added that color to your assets catalog – Joakim Danielson Jan 03 '21 at 17:22
- 
                    If you want to store colors as strings, a [hex code](https://stackoverflow.com/a/24263296/14351818) works pretty well – aheze Jan 03 '21 at 19:41
- 
                    1I'm curious why you want to do this. Are you porting code from another language? – pietrorea Jan 03 '21 at 21:01
- 
                    @PietroRea I have a .json file with colors stored by their name – nils Jan 05 '21 at 13:08
1 Answers
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
- 
                    
- 
                    @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