How do I pass a bindable object into a view inside a ForEach loop?
最低再生产法如下。
class Person: Identifiable, ObservableObject {
let id: UUID = UUID()
@Published var healthy: Bool = true
}
class GroupOfPeople {
let people: [Person] = [Person(), Person(), Person()]
}
public struct GroupListView: View {
//MARK: Environment and StateObject properties
//MARK: State and Binding properties
//MARK: Other properties
let group: GroupOfPeople = GroupOfPeople()
//MARK: Body
public var body: some View {
ForEach(group.people) { person in
//ERROR: Cannot find $person in scope
PersonView(person: $person)
}
}
//MARK: Init
}
public struct PersonView: View {
//MARK: Environment and StateObject properties
//MARK: State and Binding properties
@Binding var person: Person
//MARK: Other properties
//MARK: Body
public var body: some View {
switch person.healthy {
case true:
Text("Healthy")
case false:
Text("Not Healthy")
}
}
//MARK: Init
init(person: Binding<Person>) {
self._person = person
}
}
我的错误是<代码>。 不能在范围代码>找到人。 我的理解是,每座右翼的“inding”部分在“ForEach loop”执行期间就不属于适用范围。 我期待就一种不同模式提出建议,以在快速倡议清单中实现“具有约束力的反对”。