A newbie to SwiftUI
. I have my List
of items and I want to select one and have the TextField
take its value, mimicking an autocomplete. How can I achieve it?
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
@State private var from: String = ""
@State private var selection: String?
var body: some View {
VStack {
HStack {
TextField("From", text: $from)
.textFieldStyle(.roundedBorder)
.onChange(of: from) { newValue in
viewModel.autoComplete(input: from, flightType: .from)
}
}
}
.padding(16)
List(viewModel.suggestions, id: \.self, selection: $selection) { suggestion in
ZStack {
Text(suggestion)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
.task {
await viewModel.fetchData()
}
}
}