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?
-
1To create a color from a string you need to have added that color to your assets catalogJoakim Danielson– Joakim Danielson2021-01-03 17:22:20 +00:00Commented Jan 3, 2021 at 17:22
-
If you want to store colors as strings, a hex code works pretty wellaheze– aheze2021-01-03 19:41:29 +00:00Commented Jan 3, 2021 at 19:41
-
1I'm curious why you want to do this. Are you porting code from another language?pietrorea– pietrorea2021-01-03 21:01:06 +00:00Commented Jan 3, 2021 at 21:01
-
@PietroRea I have a .json file with colors stored by their namenils– nils2021-01-05 13:08:56 +00:00Commented Jan 5, 2021 at 13:08
Add a comment
|
1 Answer
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
}
}
}