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

How do I conditionally format SwiftUI code

if(user.reserved == "yes") {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.green)
            
            Text("\(user.name)").foregroundColor(.green)
        }
    } else if (user.reserved == "no"){
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.red)
            
            Text("\(user.name)").foregroundColor(.red)
        }
    } else if (user.reserved == "waiting") {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.orange)
            
            Text("\(user.name)").foregroundColor(.orange)
        }
    }

”’

I have this code where I want to change the appearance of the text color based on a user saying yes or no. I tried creating a var like "var color: Color" in the if statements however, it kept saying that it dit not conform to the view. How can I make conditional code effectively instead of having to copy past every thing again and again?

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

>Solution :

You could use a computed property that returns a Color based on the user’s reserved property:

struct User {
    var reserved : String
    var name : String
}

struct ContentView: View {
    @State private var user = User(reserved: "waiting", name: "Bob")
    
    var colorForReserved : Color {
        switch user.reserved {
        case "yes":
            return .green
        case "no":
            return .red
        case "waiting":
            return .orange
        default:
            return .black
        }
    }
    
    var body: some View {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark")
            Text(user.name)
        }
        .foregroundColor(colorForReserved)
    }
}

Note that you can avoid the default if you changed reserved to an enum rather than a String

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