Reputation: 805
I have a Picker
inside a View:
Form {
Section {
Picker("Style instance:", selection: $global.selectedStyle) {
ForEach(global.axes.instances.indices, id:\.self) { index in
return HStack {
let instance = global.axes.instances[index]
Text("\(instance.name)")//.tag(index)
Spacer()
Text(" \(instance.coordinates.description)")
}
}
}
.pickerStyle(PopUpButtonPickerStyle())
}
}
global
is an defined as an @ObservedObject
, inside:
@Published public var selectedStyle: StyleInstance? {
didSet {
print ("Changed \(selectedStyle?.description ?? "Nothing selected")")
if let selected = selectedStyle {
for index in axes.indices {
axes[index].at = Double(selected.coordinates[index])
}
}
}
}
StyleInstance
is simple struct:
public struct StyleInstance: Hashable, Codable {
public static var emptyName = "<normal>" //this string will be replaced by empty string
public let name: String
public let coordinates: [Int]
// init removes word `<normal>` and spaces
init(name: String, coordinates:[CoordUnit]) {
self.name = name.split(separator: " ").filter({$0 != StyleInstance.emptyName}).joined(separator: " ")
self.coordinates = coordinates.map {Int($0)}
}
}
When I change selection in Picker, selectedInstance .. {didSet..
is fired, but it's always nil
Upvotes: 0
Views: 182
Reputation: 385890
You need to apply a .tag
modifier to the HStack
inside the ForEach
. Since your selection binding is to an Optional<StyleInstance>
, you need to force the tag values to be optional also:
ForEach(global.axes.instances.indices, id:\.self) { index in
return HStack {
let instance = global.axes.instances[index]
Text("\(instance.name)")//.tag(index)
Spacer()
Text(" \(instance.coordinates.description)")
}.tag(global.axes.instances[index] as Optional)
}
Upvotes: 4