作为 swiftUI 的新手,我正在寻找一种能够在表格的某些单元格中应用颜色的方法。例如,对于“类型”类别,红色代表“束缚”,绿色代表“不受束缚”等...... 我成功地将值放入“ForEach”中,但另一方面我无法在那里集成文本。当我设法应用文本时,单元格颜色不适用。 如果我能得到你的知情意见,我会接受。谢谢你。
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)
您可以添加一个返回
Color
的函数,并使用修饰符 Color
应用该 .foregroundColor()
。如果您想更改背景颜色,请使用 .background()
修饰符。
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
}
}
}
您应该使用
List
代替,并使用 listRowBackground(_:)
设置行背景。
代码(仅相关部分,其余部分在您的问题中):
VStack {
HStack {
Text("Liste des Jailbreaks")
.font(.title)
.foregroundColor(Color.pink)
}
List {
ForEach(JailbreakList) { jailbreak in
HStack {
Text(jailbreak.noms)
.frame(maxWidth: .infinity)
Text(jailbreak.types)
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
Text(jailbreak.plateformes)
.frame(maxWidth: .infinity)
}
.listRowBackground(jailbreak.types == "Untethered" ? Color.green : Color.red)
}
}
}
结果: