【问题标题】:SwiftUI: How to set background color by color name stringSwiftUI:如何通过颜色名称字符串设置背景颜色
【发布时间】:2021-01-03 17:19:55
【问题描述】:

我有var color: String = "blue"。使用该变量,我想设置按钮的背景颜色。我试过.background(Color(color)),但这不起作用。 .background(Color.blue).background(Color(.blue)) 工作,但我想使用 String 变量。如何做到这一点?

【问题讨论】:

  • 要从字符串创建颜色,您需要将该颜色添加到资产目录
  • 如果你想将颜色存储为字符串,hex code 效果很好
  • 我很好奇你为什么要这样做。您是从其他语言移植代码吗?
  • @PietroRea 我有一个 .json 文件,其中的颜色按名称存储

标签: swift string colors swiftui


【解决方案1】:

您可以比较输入的字符串并从中获得正确的颜色。请参见以下示例:

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
        }
    }
}

【讨论】:

  • 我希望这不是必需的,但谢谢
  • @nils 我希望这样做会更容易。我刚刚从我当前的一个项目中获取了这段代码,并将其更改为最适合您
猜你喜欢
  • 1970-01-01
  • 2015-01-10
  • 2019-12-21
  • 2011-02-08
  • 1970-01-01
  • 2010-12-11
  • 2019-11-02
  • 2020-03-27
  • 1970-01-01
相关资源
最近更新 更多