[英]SwiftUI Picker doesn't select struct on MacOS
我在視圖中有一個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)}
}
}
當我在 Picker 中更改選擇時, selectedInstance .. {didSet..
被觸發,但它始終nil
您需要將.tag
修飾符應用於ForEach
內的HStack
。 由於您的選擇綁定是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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.