Home > Enterprise >  How do I conditionally format SwiftUI code
How do I conditionally format SwiftUI code

Time:03-10

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?

CodePudding user response:

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

  • Related