being new to swiftUI I am looking for a method to be able to apply a color in some cells of my table. For example for the category "Types", Red for "Tethered", Green for "Untethered" etc ... I succeeded by putting values in "ForEach" but on the other hand I can not integrate text there. And when I manage to apply the text, the cell colors don't apply. If I could have your informed opinions, I am a taker. Thank you.
struct Jailbreak: Identifiable {
let id = UUID()
let noms: String
let types: String
let plateformes: String
}
struct AnnuaireView: View {
var JailbreakList = [
Jailbreak(noms: "Unc0ver", types: "Semi-Untethered", plateformes: "iOS/iPadOS"),
Jailbreak(noms: "Pangu9", types: "Untethered", plateformes: "iOS/tvOS")
]
let gridItems = [
GridItem(.flexible(), spacing: 3.0, alignment: .center),
GridItem(.flexible(), spacing: 3.0, alignment: .center),
GridItem(.flexible(), spacing: 3.0, alignment: .center),
]
var body: some View {
VStack {
HStack {
Text("Liste des Jailbreaks")
.font(.title)
.foregroundColor(Color.pink)
}
ScrollView(.vertical) {
LazyVGrid(columns: gridItems, alignment: .center, spacing: 10) {
ForEach(JailbreakList){ Jailbreak in
Text(Jailbreak.noms)
Text(Jailbreak.types)
.multilineTextAlignment(.center)
Text(Jailbreak.plateformes)
You can add a function that returns a Color
and apply that Color
with the modifier .foregroundColor()
. If you want to change the background color instead, use the .background()
modifier.
struct AnnuaireView: View {
var JailbreakList = [
Jailbreak(noms: "Unc0ver", types: "Semi-Untethered", plateformes: "iOS/iPadOS"),
Jailbreak(noms: "Pangu9", types: "Untethered", plateformes: "iOS/tvOS")
]
let gridItems = [
GridItem(.flexible(), spacing: 3.0, alignment: .center),
GridItem(.flexible(), spacing: 3.0, alignment: .center),
GridItem(.flexible(), spacing: 3.0, alignment: .center),
]
var body: some View {
VStack {
HStack {
Text("Liste des Jailbreaks")
.font(.title)
.foregroundColor(Color.pink)
}
ScrollView(.vertical) {
LazyVGrid(columns: gridItems, alignment: .center, spacing: 10) {
ForEach(JailbreakList){ Jailbreak in
Text(Jailbreak.noms)
Text(Jailbreak.types)
.multilineTextAlignment(.center)
.foregroundColor(getColor(for: Jailbreak))
Text(Jailbreak.plateformes)
}
}
}
}
}
private func getColor(for jailbreak: Jailbreak) -> Color {
switch jailbreak.types {
case "Untethered":
return Color.red
case "Semi-Untethered":
return Color.orange
case "Tethered":
return Color.green
default:
return Color.black
}
}
}