#swift #swiftui
#swift #swiftui
Вопрос:
У меня есть Picker
внутреннее представление:
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
определяется как @ObservedObject
, внутри:
@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
это простая структура:
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)}
}
}
Когда я меняю выделение в средстве выбора, selectedInstance .. {didSet..
запускается, но это всегда nil
Ответ №1:
Вам нужно применить .tag
модификатор к HStack
внутренней ForEach
части . Поскольку ваша привязка к выбору привязана к an Optional<StyleInstance>
, вам также необходимо сделать значения тегов необязательными:
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)
}