0

Hopefully you can see what I'm trying to achieve from the code below but simply put, I'm trying to update .selectedTown which is binded to my Picker. The row tapped on will bind to .selectedTown which will then update the Text 'Your selected town is: [.selectedTown]' However, the selected row is not binding and the text remains 'Your selected town is: '

struct ContentView: View { struct Town: Identifiable { let name: String let id = UUID() } private var towns = [ Town(name: "Bristol"), Town(name: "Oxford"), Town(name: "Portsmouth"), Town(name: "Newport"), Town(name: "Glasgow"), ] @State private var selectedTown: String = "" var body: some View { NavigationView { VStack { Form { Section { Picker("", selection: $selectedTown) { ForEach(towns, id: \.id) { Text("\($0.name)") } } .pickerStyle(.inline) .labelsHidden() } header: { Text("Random Towns") } } Text("Your selected town is: \(selectedTown)") .padding() } .navigationTitle("Random") } } 

}

Hopefully this is just a small fix but I've tried for what seems a day to find a solutino and am now stuck. Any help would be gratefully received,

Simon

2 Answers 2

1

The types don't match. your array is a towns: [Town] and your selectedTown: String

Option 1 is to change the variable

@State private var selectedTown: Town = Town(name: "Sample") 

Option 2 is to add a tag

Text("\($0.name)").tag($0.name) 

Option 3 is change the variable and the tag

@State private var selectedTown: Town? = nil Text("\($0.name)").tag($0 as? Town) 

The "best" option depends on what you use selectedTown for.

Sign up to request clarification or add additional context in comments.

Comments

1

The type of selection should be same as picked item or use tag, like below

demo

Picker("", selection: $selectedTown) { ForEach(towns, id: \.id) { Text("\($0.name)").tag($0.name) // << here !! } } 

Tested with Xcode 13.2 / iOS 15.2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.