SwiftUI:如何按颜色名称字符串设置背景色
我有SwiftUI:如何按颜色名称字符串设置背景色,swift,string,colors,swiftui,Swift,String,Colors,Swiftui,我有var-color:String=“blue”。我想用这个变量设置按钮的背景色。我尝试了.background(Color(Color)),但没有成功.background(Color.blue)或.background(Color(.blue))工作,但我想使用字符串变量。如何做到这一点?您可以比较输入的字符串并从中获得正确的颜色。请参见以下示例: struct ContentView: View { var body: some View { Color
var-color:String=“blue”
。我想用这个变量设置按钮的背景色。我尝试了.background(Color(Color))
,但没有成功.background(Color.blue)
或.background(Color(.blue))
工作,但我想使用字符串变量。如何做到这一点?您可以比较输入的字符串并从中获得正确的颜色。请参见以下示例:
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
}
}
}
若要从字符串创建颜色,您需要将该颜色添加到资源目录中。若要将颜色存储为字符串,a工作得非常好。我很好奇您为什么要这样做。您是从另一种语言移植代码吗?@PietroRea我有一个.json文件,其中的颜色按名称存储。我希望这不是必需的,但谢谢you@nils我希望这样做会容易些。我只是从我当前的一个项目中提取了这段代码,并将其更改为最适合您的代码