SwiftUI - 更新 ForEach 循环中的变量以替换列表的背景颜色
SwiftUI - Update variable in ForEach Loop to alternate background color of a list
我尝试为列表实现一个 pingpong 变量,这样我就可以改变背景颜色。出于某种原因,下面抛出错误,但编译器只是说 "Failed to Build." 当我从视图中删除 "switchBit" 函数调用时,它编译正常。有人可以帮助我了解我在这里做错了什么吗?
struct HomeScreen: View {
let colors: [Color] = [.green,.white]
@State var pingPong: Int = 0
var body: some View {
NavigationView{
GeometryReader { geometry in
ScrollView(.vertical) {
VStack {
ForEach(jobPostingData){jobposting in
NavigationLink(destination: jobPostingPage()) {
JobListingsRow(jobposting: jobposting).foregroundColor(Color.black).background(self.colors[self.pingPong])
}
self.switchBit()
}
}
.frame(width: geometry.size.width)
}
}
.navigationBarTitle(Text("Current Listed Positons"))
}
}
func switchBit() {
self.pingPong = (self.pingPong == 1) ? 0 : 1
}
}
我猜你想为行替换颜色。您将不得不避免使用 switchBit 代码并使用类似下面的代码来切换颜色:
struct Homescreen: View {
let colors: [Color] = [.green,.white]
@State var jobPostingData: [String] = ["1","2", "3","4"]
@State var pingPong: Int = 0
var body: some View {
NavigationView{
GeometryReader { geometry in
ScrollView(.vertical) {
VStack {
ForEach(self.jobPostingData.indices, id: \.self) { index in
JobListingsRow(jobposting: self.jobPostingData[index])
.foregroundColor(Color.black)
.background(index % 2 == 0 ? Color.green : Color.red)
}
}
.frame(width: geometry.size.width)
}
}
.navigationBarTitle(Text("Current Listed Positons"))
}
}
}
我尝试为列表实现一个 pingpong 变量,这样我就可以改变背景颜色。出于某种原因,下面抛出错误,但编译器只是说 "Failed to Build." 当我从视图中删除 "switchBit" 函数调用时,它编译正常。有人可以帮助我了解我在这里做错了什么吗?
struct HomeScreen: View {
let colors: [Color] = [.green,.white]
@State var pingPong: Int = 0
var body: some View {
NavigationView{
GeometryReader { geometry in
ScrollView(.vertical) {
VStack {
ForEach(jobPostingData){jobposting in
NavigationLink(destination: jobPostingPage()) {
JobListingsRow(jobposting: jobposting).foregroundColor(Color.black).background(self.colors[self.pingPong])
}
self.switchBit()
}
}
.frame(width: geometry.size.width)
}
}
.navigationBarTitle(Text("Current Listed Positons"))
}
}
func switchBit() {
self.pingPong = (self.pingPong == 1) ? 0 : 1
}
}
我猜你想为行替换颜色。您将不得不避免使用 switchBit 代码并使用类似下面的代码来切换颜色:
struct Homescreen: View {
let colors: [Color] = [.green,.white]
@State var jobPostingData: [String] = ["1","2", "3","4"]
@State var pingPong: Int = 0
var body: some View {
NavigationView{
GeometryReader { geometry in
ScrollView(.vertical) {
VStack {
ForEach(self.jobPostingData.indices, id: \.self) { index in
JobListingsRow(jobposting: self.jobPostingData[index])
.foregroundColor(Color.black)
.background(index % 2 == 0 ? Color.green : Color.red)
}
}
.frame(width: geometry.size.width)
}
}
.navigationBarTitle(Text("Current Listed Positons"))
}
}
}