I've got an array of strings that I want to present using swiftUI Picker widget. Each string is composed of multiple words delimited by spaces.
I'd like to get the Picker showing the full string of each item in the list, while the selection variable should only get the first word (the selected item is stored in arg)
This was my attempt to do so. notice that the object that hold the items called myHandler, and it's shared to the swiftUI view, and can be modified by external swift closure:
class myHandler: ObservableObject {
@Published var items = [String]()
}
struct ContentView: View {
@State var arg: String = ""
@ObservedObject var handler : myHandler
...
VStack {
Picker("items", selection: $arg) {
Text("AAA").tag("***")
Text("BBB").tag("yyy")
Text("CCC").tag("zzz")
ForEach(handler.items , id: \.self, content: {
Text($0).tag($0.components(separatedBy: " ")[0])
})
}
}
.frame()
TextField("firstword", text: $arg).frame()
For the options outside the ForEach statement, I can see that arg get the value written in the tag.
However, for all options that derived from the ForEach, I see that arg equals to the iterable item ($0) which is the multi work string, and not to the first word as expected.
Any idea how to fix those items that are generated from the ForEach, so that selection of such item, will set the arg to the string value of the first word in the iterator ?