I have a problem with the binding of a picker. Here a short sample project. A simple data structure with two fields: a string (f1) and an enum (f2).
struct D0: Identifiable,Equatable {
var id: UUID
var f1:String
var f2:T0
}
extension D0 {
struct Data {
var f1:String = String()
var f2:T0 = .s1
}
var data:Data {Data(f1: f1, f2: f2)}
init(data:Data) {
self.id = UUID()
self.f1 = data.f1
self.f2 = data.f2
}
mutating func update(from data:Data) {
self.f1 = data.f1
self.f2 = data.f2
}
static let sampleData : [D0] = [
D0(id: UUID(), f1: "string1", f2: .s1),
D0(id: UUID(), f1: "string2", f2: .s2)
]
enum T0: Int,CaseIterable,Identifiable {
case s1=1
case s2
var id:Self {self}
var name:String {
switch rawValue {
case 1:
return "one"
case 2:
return "two"
default:
return "undefined"
}
}
In the Editing View the string is bound to a textfield while the enum field is bound to the selection of a Picker.
struct Editing: View {
@Binding var data:D0.Data
var body: some View {
Form {
VStack {
TextField("F1", text: $data.f1)
Picker("F2", selection: $data.f2) {
ForEach(T0.allCases) { t0 in
Text(t0.name)
.tag(t0)
}
}
}
}
}
}
Data are presented in a list with three sections:
- data from the binding to the whole data
- subset of data having f2 equal to .s1
- subset of data having f2 equal to .s2
struct mList: View {
@Binding var all:[D0]
func segmentByState(state:T0) -> [D0] {
return all.filter { d in
d.f2 == state
}
}
var body: some View {
List {
Section("All") {
ForEach($all) { $a in
NavigationLink(destination: {
Details(d0: $a)
}) {
Cell(d0: a)
}
}
}
Section("S1") {
ForEach(segmentByState(state: .s1)) { a in
//look for the index of the object in the binding
let ind:Int = all.firstIndex(of: a)!
NavigationLink(destination: {
// pass the bound element
Details(d0: $all[ind])
}) {
Cell(d0: a)
}
}
}
Section("S2") {
ForEach(segmentByState(state: .s2)) { a in
//look for the index of the object in the binding
let ind:Int = all.firstIndex(of: a)!
NavigationLink(destination: {
// pass the bound element
Details(d0: $all[ind])
}) {
Cell(d0: a)
}
}
}
}
}
}
Changing the f2 value move the rows in the right section (2 or 3) but its name is updated only in the first section while in the others it remains the previous one.
Changing the f1 value it works correctely,
How should I bound data to have the name correctly presented?
Thank you.