我想生成一个带有 ForEach 循环的输入 TextFields 列表。 textFields 显然是@State 变量。
我确实得到了错误:
Generic struct 'ForEach' requires that 'Binding' conform to 'Hashable'
这是我的代码:
struct ContentView: View {
@State private var mainPrice = ""
@State private var mainGrade = ""
var body: some View {
var inputFields = [$mainPrice,$mainGrade]
HStack {
List{
ForEach(inputFields, id: \.self) { value in /// here is the error
TextField("Enter data", text: value)
}
}
}
}
因此,我将绑定(bind)变量放在一个数组中,因为我需要在循环中使用绑定(bind)类型,也许这不是该怎么做?我试图将 Hashable
添加到 inputFields var 以响应错误消息,但我怀疑整个设置是错误的。
最佳答案
import SwiftUI
struct ContentView: View {
@State private var mainPrice = ""
@State private var mainGrade = ""
var body: some View {
let inputFields = [BindingWrapper(binding: $mainPrice), BindingWrapper(binding: $mainGrade)]
HStack {
List{
ForEach(inputFields, id: \.uuid) { value in /// here is the error
TextField("Enter data", text: value.$binding)
}
}
}
}
}
struct BindingWrapper {
let uuid: UUID = UUID()
@Binding var binding: String
}
关于swiftui - 无法在使用 SwiftUI 的 ForEach 循环中获取 @state 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64687681/