【问题标题】:SwiftUI - Increment variable in a ForEach loopSwiftUI - ForEach 循环中的增量变量
【发布时间】:2020-06-23 22:10:36
【问题描述】:

我的ContentView 中有这个:

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 是一名建设者。你能解释一下吗?

标签: swiftui


【解决方案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)
    }
}

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

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

【讨论】:

  • 谢谢你。代码的唯一问题是 cellColor 需要是 CGFloat: Cannot convert value of type 'Binding' to expected argument type 'Binding'
  • 您所要做的就是将代码从 Binding&lt;Color&gt; 更改为 Binding&lt;CGFloat&gt; 就像错误所说的那样......就像我在帖子中所说的那样,你没有在你的问题中说什么所有变量的类型都是所以我不得不猜测。请参阅我的编辑。 @尼克
  • 您没有错误“在视图更新期间修改状态,这将导致未定义的行为。”
  • 不起作用,原因是 Michael Ziobro 刚才说的。不应该有绿色复选标记。我会发布一个更好的方法。
猜你喜欢
  • 2020-05-26
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多