I have created a form in SwiftUI, now I am trying to add a search bar and make the List searchable without system built NavigationView. I was wondering is there any possible way to do so?
CodePudding user response:
One easy way is you can customise TextField in SwiftUI, via text field text to filter data.
struct Sample006: View {
@State var dataSource: [String] = ["1", "2", "3"]
@State var filterData: [String] = []
@State var filterText: String = ""
var body: some View {
VStack {
TextField("Input Text", text: self.$filterText)
.textFieldStyle(.roundedBorder)
.padding(.horizontal, 20)
Form {
ForEach(filterData, id: \.self) { data in
Text(data)
}
}
}
.onAppear {
reset()
}
.onChange(of: filterText) { newValue in
guard !newValue.isEmpty else {
reset()
return
}
filterData = dataSource.filter { text in
text == newValue
}
}
}
private func reset() {
filterData = dataSource
}
}