[英]SwiftUI Picker doesn't select struct on MacOS
I have a Picker
inside a View:我在视图中有一个
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
is an defined as an @ObservedObject
, inside: 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
is simple struct: 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)}
}
}
When I change selection in Picker, selectedInstance .. {didSet..
is fired, but it's always nil
当我在 Picker 中更改选择时,
selectedInstance .. {didSet..
被触发,但它始终nil
You need to apply a .tag
modifier to the HStack
inside the ForEach
.您需要将
.tag
修饰符应用于ForEach
内的HStack
。 Since your selection binding is to an Optional<StyleInstance>
, you need to force the tag values to be optional also:由于您的选择绑定是
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.