SwiftUI:如何使用字符串将颜色设置为 .foregroundColor()?即 "green" --> Color.green

SwiftUI: How can I set a color to .foregroundColor() by using a String? i.e. "green" --> Color.green

所以我在常量 (lernset.color 中有这个字符串“green”。我想将 .foregroundColor() 设置为列表内的符号 (systemName: "folder"),使其颜色与常量 (lernset.color). 我遇到的问题:我不知道如何将这个具有字符串数据类型的常量 (lernset.color) 转换为颜色数据类型。 我已经试过了:

  1. ....foregroundColor(Color.lernset.color)
  2. ....foregroundColor(Color.String(lernset.color))
  3. 我也尝试过将常量分配给变量...但是

没有任何效果。

[所以通常你会输入:.foregroundColor(Color.green) 但在这种情况下,我希望列表自动适应,以便颜色可以改变常量 (lernset.color) 变化的方式...

提前感谢您的帮助

使用

Color(lernset.color)

仅当 lernset.colorString 值定义为 Assets

中的 Color Set 时才有效

这个

Color.lernset.color

Color.green

引用一个 static 变量。你需要像

这样的东西
extension Color{
    static let yourColor: Color = Color("nameHere")
}

那你可以打电话

Color.yourColor

“nameHere”是 Color Set

的名称

如果您想使用字符串,您可以为 Color 添加扩展名:

extension Color {
    static subscript(name: String) -> Color {
        switch name {
            case "green":
                return Color.green
            case "white":
                return Color.white
            case "black":
                return Color.black
            default:
                return Color.accentColor
        }
    }
}

用法:

Color[lernset.color]