I want to render a list of results from an API I've built and as a quick visual reference for people to see if the status is red, amber or green.
I can send the information back as a string or int I'm not really precious about how but I can't get the foreground colour to change on the sf symbol I'm using which is circle.fill
I'm not sure what the best way to feed the data into SwiftUI is as I can't just declare a string for my colour name.
At the moment it's from a variable name that is part of my struct but I need a way for this to ideally be a string or an int. Is there a way in swift that I can pass a colour to a modifier?
struct Insight: Identifiable {
let id = UUID()
let title: String
let description: String
let statusColor: Color
let header: String
}
let red: Color = Color(.red)
let yellow: Color = Color(.yellow)
let green: Color = Color(.green)
struct InsightList {
static let topTenInsights = [
Insight(title: "Some text",
statusColor: red,
header: "Header"),
Finsight(title: "Some text",
statusColor: red,
header: "Income")
]
}
var insights: [insight] = insightList.topTenInsights
struct Landing: View {
let user = Auth.auth().currentUser
let red: Color = Color(.red)
let yellow: Color = Color(.yellow)
let green: Color = Color(.green)
var body: some View {
List(insights, id: \.id) { userinsight in
HStack {
Image(systemName: "circle.fill").foregroundStyle(insight.statusColor)
.scaledToFit()
.padding()
.shadow(radius: 0.9)
VStack(alignment: .leading, spacing: 8) {
Text("Category: \(insight.header)")
.fontWeight(.semibold)
.lineLimit(2)
.minimumScaleFactor(0.5)
Text(insight.title)
.fontWeight(.light)
.lineLimit(2)
.minimumScaleFactor(0.9)
}.padding(13)
.shadow(radius: 0.3)
}
}
}
}
CodePudding user response:
you could do something simple like this:
func getStatusColor(_ status: Int) -> Color {
switch status {
case 0: return Color.red
case 1: return Color.yellow
case 2: return Color.green
default: return Color.blue
}
}
Image(systemName: "circle.fill")
.foregroundStyle(getStatusColor(statusValue))
.....