我尝试实现一个“乒乓”变量,这样我就可以在
VStack
中交替视图的背景颜色。
由于某种原因,下面的代码不起作用并导致编译器报告
"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 Positions"))
}
}
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"))
}
}
}