Reputation: 905
I am working with SwiftUI, I have one switch case function, depend on that switch case i want to show diff color and text.
func status(status: Status){
switch status {
case .accepted:
//text "accepted"
//green text
case .standby:
//text "standby"
//yellow text
case .notAllowed:
//text "notAllowed"
//red text
}
}
VStack(alignment: .leading) {
Text("Test")
}
Upvotes: 1
Views: 1489
Reputation: 54735
You can simply switch over status
inside the body of your view and assign the correct String
and foregroundColor
to your Text
inside each `case.
struct StatusView: View {
let status: Status
var body: some View {
switch status {
case .accepted:
Text("accepted")
.foregroundColor(.green)
case .standby:
Text("standby")
.foregroundColor(.yellow)
case .notAllowed:
Text("not allowed")
.foregroundColor(.red)
}
}
}
Or if you can modify Status
, you can simply assign a String
rawValue
to it, then displaying the appropriate text based on its value is even easier.
enum Status: String {
case accepted
case standby
case notAllowed
}
struct StatusView: View {
let status: Status
var body: some View {
Text(status.rawValue)
.foregroundColor(statusColor(status: status))
}
private func statusColor(status: Status) -> Color {
switch status {
case .accepted:
return .green
case .standby:
return .yellow
case .notAllowed:
return .red
}
}
}
Upvotes: 2
Reputation: 1
Here is an updated and refactored answer based on David answer, with this way you do not need that ststusColor
function anymore and you can access the colorValue every where in your project instead of last answer that was accessible only inside StatusView
.
struct StatusView: View {
let status: Status
var body: some View {
Text(status.rawValue)
.foregroundColor(status.colorValue)
}
}
enum Status: String {
case accepted
case standby
case notAllowed
var colorValue: Color {
switch self {
case .accepted:
return .green
case .standby:
return .yellow
case .notAllowed:
return .red
}
}
}
Upvotes: 0