swiftui - SwiftUI - 更新 ForEach 循环中的变量以替换列表的背景颜色
问题描述
我尝试为列表实现一个 pingpong 变量,以便可以交替背景颜色。出于某种原因,以下抛出和错误,但编译器只是说“构建失败”。当我从视图中删除“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"))
}
}
}
推荐阅读
- meteor - Meteor Id 防碰撞缩短
- selenium - 带有复选框的下拉菜单,需要使用 select 功能选择和取消选择复选框并使用 selenium 获取关联的值
- microservices - 微服务架构中客户端到 API 网关的通信
- php - 为什么我得到 Class '\App\Teacher' not found 错误
- vb.net - 将字体样式更改为 Richtextbox vb.net
- java - 使用 Apache Spark Java“转换”传感器数据
- java - 错误:类 Droid 中的构造函数 Droid 不能应用于给定类型;
- sql-server - 如何使用 docker 在 nginx 上部署具有 angular 6 作为前端、后端为 Asp dot net core 和 SQL 服务器作为数据库的 Web 应用程序
- java - java WebProject的依赖jar文件的ClassNotFoundException
- algorithm - 在单链表和双链表中删除的时间复杂度是多少?