5 swiftui
我的ContentView:
List {
ForEach(items) { Item in
ItemView(cellColor: self.$cellColor, title: item.title, orderId: "\(item.orderId)")
}
}
Run Code Online (Sandbox Code Playgroud)
我想更新一个变量,假设在循环的每次迭代中向其添加 1,但我无法让 SwiftUI 执行此操作。像这样的东西:
var a: Int = 1
List {
ForEach(toDoItems) { toDoItem in
ToDoItemView(cellColor: self.$cellColor, title: toDoItem.title, orderId: "\(toDoItem.orderId)")
a = a + 1
}
}
Run Code Online (Sandbox Code Playgroud)
但这是行不通的。抱歉,如果我没有以正确的格式提出这个问题,这是我的第一个问题!
创建一个函数,返回 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)
}
}
Run Code Online (Sandbox Code Playgroud)
cellColor您没有指定、title和的类型orderId,因此我只是根据其余代码的上下文进行猜测。您应该能够很容易地调整类型,但如果不能,请确定问题中变量的类型或本文的评论,我可以更新我的答案(但我很确定我的类型是正确的)。
编辑:显然cellColor是 a CGFloat,而不是Color根据 OP 的评论,所以我更新了我的代码以反映这一点。
| 归档时间: |
|
| 查看次数: |
8003 次 |
| 最近记录: |