在绑定调用中使用SwiftUI ForEach的迭代器变量

时间:2020-02-13 14:47:45

标签: ios swiftui

我试图在需要绑定的视图中使用ForEach的iterator变量。

import SwiftUI

struct MyStruct: Identifiable {
    public var id = UUID()
    var name: String
    var repetitions: Int

}

struct ContentView: View {
    @State private var mystructs :[MyStruct] = [
        MyStruct(name: "John", repetitions: 3),
        MyStruct(name: "Mark", repetitions: 9)
    ]

    var body: some View {

        List {
            ForEach (mystructs) { st in
                VStack {
                    Text("\(st.name)")
                    TextField("Name", text: self.$mystructs[0].name)
                    TextField("Name", text: $st.name) // <- Got "Ambiguous reference..." error
                }
            }
        }
    }
}

ForEach迭代器有效,如Text视图对st.name的使用所示。第一个TextField演示了绑定到mystructs元素的工作原理。但是,对于第二个TextField(这是我的实际用例),会导致以下编译器错误:

- Use of unresolved identifier $st
- Ambiguous reference to member of 'subscript'

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

$ st即将出现,因为'st'不是状态变量,因此不能用于绑定。
$ mystructs也是有效的,因为它已声明为State变量,可用于绑定。

希望这对您有用!谢谢!

答案 1 :(得分:1)

在上述情况下,可以执行以下操作

ForEach (mystructs.indices) { i in
    VStack {
        Text("\(self.mystructs[i].name)")
        TextField("Name", text: self.$mystructs[i].name)
    }
}

更新:适用于更多通用用例的变体

ForEach (Array(mystructs.enumerated()), id: \.element.id) { (i, item) in
    VStack {
        Text("\(item.name)")
        TextField("Name", text: self.$mystructs[i].name)
    }
}

答案 2 :(得分:1)

以@Asperi的答案为基础,这也有效:

var body: some View {
    List {
        Button("Add") {
            self.mystructs.append(MyStruct(name: "Pepe", repetitions: 42))
        }
        ForEach(mystructs.indices, id: \.self) { index in
            VStack {
                Text(self.mystructs[index].name)
                TextField("Name", text: self.$mystructs[index].name)
            }
        }
    }
}