Estoy trabajando con SwiftUI, tengo una función de caso de cambio, depende de ese caso de cambio que quiero mostrar color y texto diferentes.
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") }Simplemente puede cambiar el status dentro del cuerpo de su vista y asignar la String y el color de foregroundColor correctos a su Text dentro de cada caso.
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) } } } O si puede modificar Status , simplemente puede asignarle un String rawValue , luego mostrar el texto apropiado en función de su valor es aún más fácil.
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 } } }Aquí hay una respuesta actualizada y refactorizada basada en la respuesta de David , de esta manera ya no necesita esa función ststusColor y puede acceder a colorValue en todas partes de su proyecto en lugar de la última respuesta a la que solo se podía acceder dentro 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 } } }