1

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("xxx") 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 ?

3
  • What is handler? Can you include a minimal reproducible example? And, can you clarify what the purpose of the TextField is (ie what it should be updating)? Is it supposed to be an editor for just the first word of arg? Commented Feb 9, 2022 at 19:48
  • @jnpdx, I tried to make it more clear. The main thing here is to use different values on the textField and in the Picker items Commented Feb 9, 2022 at 20:01
  • I think I get the gist of the first issue, with the picker (you'll need to use .tag to assign a custom tag to each item), but I'm still very unclear of the purpose of the TextField here. Maybe someone else will understand better. Commented Feb 9, 2022 at 20:04

1 Answer 1

1
Picker("items", selection: $arg) { ForEach(handler.items, id: \.self) { Text($0) .tag($0.components(separatedBy: " ").first ?? "") } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Hi and thanks for the help ... I've read about the .tag in the documentation and it indeed seem to be the way to achieve my goal. However, for some reason, no matter how I set the tag value, I keep getting the full string in the textField ... maybe I'm missing something ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.