在使用SwiftUI的ForEach循环中无法获取@state变量

时间:2020-11-04 21:02:15

标签: swiftui

我想生成一个带有ForEach循环的输入TextField的列表。 textFields显然是@State变量。

我确实得到了错误:

通用结构“ ForEach”要求“ Binding”符合 “可散列”

这是我的代码:

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)

                    }
                }
        }
       
    }

因此,我将绑定变量放入数组中,因为我在循环中需要绑定类型,也许那不是怎么做的?我试图将Hashable添加到inputFields var中以响应错误消息,但是我怀疑整个设置是错误的。

3 个答案:

答案 0 :(得分:2)

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
}

答案 1 :(得分:1)

struct ContentView: View {
    @State private var mainPrice = ["1000", "5000"]

    var body: some View {
        HStack {
            List {
                ForEach(mainPrice.indices, id: \.self) { index in
                    TextField("Enter data", text: $mainPrice[index])
                }
            }
        }
    }
}

答案 2 :(得分:0)

我实际上发现了使用具有id的结构执行此操作的另一种方法,因为主要问题似乎是该数组未提供数据的准确标识。我们需要一个ID(请参阅视频https://www.hackingwithswift.com/books/ios-swiftui/working-with-identifiable-items-in-swiftui):

struct tableContent{
    var id: Int
    var label: String
    var data: Binding<String>
}

该数组如下所示:

let textFields = [
            tableContent(id: 1, data: $mainPrice),
            tableContent(id: 2, data: $mainGrade)
        ]

还有ForEach循环

List{
     ForEach(textFields, id: \.id)  { value in
         TextField("", text: value.data)
         }
     }