SwiftUI - 在 ForEach 循环中递增变量

问题描述:

我的 ContentView 中有这个:

List {
    ForEach(items) { Item in
        ItemView(cellColor: self.$cellColor, title: item.title, orderId: "\(item.orderId)")
    }
}

我想更新一个变量,比如在循环的每次迭代中给它加 1,但我无法让 SwiftUI 做到这一点.像这样:

I want to update a variable, let's say by adding 1 to it, on each iteration of the loop, but I can't get SwiftUI to do that. Something like this:

var a: Int = 1
List {
    ForEach(toDoItems) { toDoItem in
        ToDoItemView(cellColor: self.$cellColor, title: toDoItem.title, orderId: "\(toDoItem.orderId)")
        a = a + 1
    }
}

但这行不通.抱歉,如果我没有以正确的格式提出这个问题,这是我在这里的第一个问题!

But that doesn't work. Apologies if I've not asked this in the correct format, This is my first question here!

创建一个函数,该函数返回您在 ForEach 中想要的视图并增加变量.

Make a function that returns the view you want in the ForEach and also increments the variable.

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)
    }
}

您没有指定 cellColortitleorderId 的类型,所以我只是从其余部分的上下文中猜测你的代码.您应该能够很容易地调整类型,但如果没有,请确定您的问题或这篇文章的评论中的变量类型,我可以更新我的答案(但我很确定我的类型是正确的).

You didn't specify the types of cellColor, title, and orderId, so I just guessed from the context of the rest of your code. You should be able to adjust the types pretty easily, but if not, identify the types of the variables in your question or the comments of this post and I can update my answer (but I'm pretty sure I got the types right).

Edit:根据 OP 的评论,显然 cellColorCGFloat,而不是 Color,所以我更新了我的代码来反映这一点.

Edit: Apparently cellColor is a CGFloat, not a Color according to OP's comment, so I updated my code to reflect that.