[英]Using SwiftUI ForEach's iterator variable in a binding call
我试图在需要绑定的视图中使用 ForEach 的迭代器变量。
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'
有什么想法吗?
$st 未解决,因为 'st' 不是状态变量,不能用于绑定目的。
另外 $mystructs 正在工作,因为它被声明为 State 变量并可用于绑定。
希望这对你有用!谢谢!
在描述的场景中,可以执行以下操作
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)
}
}
基于@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)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.