Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

So I have this String "green" inside a constant (lernset.color). I would like to set a .foregroundColor() to a symbol (systemName: "folder") inside of a list, so that it has the same color as written inside the constant (lernset.color).
The problem I get: I dont know how to convert this constant (lernset.color) which has the datatype of a String into the datatype of Color.
I already tried:

  1. .foregroundColor(Color.lernset.color)
  2. .foregroundColor(Color.String(lernset.color))
  3. I also tried assigning the constant to a variable… but

nothing worked.

[ So normally you would type: .foregroundColor(Color.green)
But in this case I want the List to automatically adapt, so that the Color could change the way the constant (lernset.color) changes…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you for your help in advance

>Solution :

Use

Color(lernset.color)

It only works if the String value of lernset.color is defined as a Color Set in Assets

This

Color.lernset.color

or

Color.green

References a static variable. You would need something like

extension Color{
    static let yourColor: Color = Color("nameHere")
}

Then you can call

Color.yourColor

With "nameHere" being the name of a Color Set

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading