SwiftUI-ForEach循环中的增量变量
我在我的SwiftUI-ForEach循环中的增量变量,swiftui,Swiftui,我在我的内容视图中有以下内容: List { ForEach(items) { Item in ItemView(cellColor: self.$cellColor, title: item.title, orderId: "\(item.orderId)") } } 我想在循环的每次迭代中更新一个变量,比如说向它添加1,但我不能让SwiftUI这样做。大概是这样的: var a: Int = 1 List { ForEach(toDoItems) {
内容视图中有以下内容:
List {
ForEach(items) { Item in
ItemView(cellColor: self.$cellColor, title: item.title, orderId: "\(item.orderId)")
}
}
我想在循环的每次迭代中更新一个变量,比如说向它添加1,但我不能让SwiftUI这样做。大概是这样的:
var a: Int = 1
List {
ForEach(toDoItems) { toDoItem in
ToDoItemView(cellColor: self.$cellColor, title: toDoItem.title, orderId: "\(toDoItem.orderId)")
a = a + 1
}
}
但这不起作用。抱歉,如果我问的格式不正确,这是我的第一个问题 生成一个函数,该函数返回ForEach中所需的视图,并增加变量
struct ContentView: View {
@State var a: Int = 1
@State var cellColor: CGFloat = 0.0 // or whatever this is in your code
var body: some View {
List {
ForEach(toDoItems) { toDoItem in
self.makeView(cellColor: self.$cellColor, title: toDoItem.title, orderId: "\(toDoItem.orderId)")
}
}
}
func makeView(cellColor: Binding<CGFloat>, title: String, orderId: String) -> ToDoItemView {
self.a += 1
return ToDoItemView(cellColor: cellColor, title: title, orderId: orderId)
}
}
struct ContentView:View{
@状态变量a:Int=1
@State var cellColor:CGFloat=0.0//或代码中的任何内容
var body:一些观点{
名单{
ForEach(toDoItems){toDoItem in
self.makeView(cellColor:self.$cellColor,title:toDoItem.title,orderId:“\(toDoItem.orderId)”)
}
}
}
func makeView(cellColor:Binding,title:String,orderId:String)->ToDoItemView{
self.a+=1
返回到DoItemView(cellColor:cellColor,title:title,orderId:orderId)
}
}
您没有指定cellColor
、title
和orderId
的类型,因此我只是根据代码其余部分的上下文猜测。你应该能够很容易地调整类型,但如果不能,请在你的问题或这篇文章的评论中确定变量的类型,我可以更新我的答案(但我很确定我得到了正确的类型)
Edit:根据OP的评论,显然cellColor
是一种CGFloat
,而不是Color
,所以我更新了我的代码以反映这一点。你对循环的每次迭代是什么意思ForEach
是一个生成器。你能再解释一下吗?谢谢你。代码的唯一问题是cellColor需要是CGFloat:无法将“Binding”类型的值转换为预期的参数类型“Binding”。您需要做的就是将代码从Binding
更改为Binding
,就像错误所说的那样。。。就像我在帖子里说的,你在问题中没有说所有变量的类型,所以我不得不猜测。请参阅我的编辑@NickYou没有错误“在视图更新期间修改状态,这将导致未定义的行为。”