Hi everyone, I can not find the solution. So, how to add UISearchController in SwiftUI? I would like to implement it as App Store app on iOS. Like this:
My current code:
struct EmployeesView: View {
@State var employees: [Employee] = []
@State private var showAlert = false
@State private var searchText : String = ""
enum Alert {
case filter
}
var body: some View {
NavigationView {
List {
Group {
SearchBar(text: $searchText)
ForEach(employees) { employee in
NavigationLink(destination: EmployeeView(employee: employee)) {
EmployeeRowView(employee: employee)
}
}
}
}
.navigationBarTitle("List of employees")
.navigationBarItems(trailing:
Button(action: {
self.showAlert = true
}, label: {
Text("Filter")
})
)
.navigationViewStyle(StackNavigationViewStyle())
}
.actionSheet(isPresented: $showAlert) {
ActionSheet(
title: Text("Options"),
buttons: [
.default(Text("All"), action: {}),
.default(Text("Online"), action: {}),
.default(Text("Monitored"), action: {}),
.default(Text("Online idle"), action: {}),
.cancel()
])
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.employees.append(contentsOf: Employee.testData)
}
}
}
}
struct SearchBar: UIViewRepresentable {
@Binding var text: String
class Coordinator: NSObject, UISearchBarDelegate {
@Binding var text: String
init(text: Binding) {
_text = text
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
}
}
func makeCoordinator() -> SearchBar.Coordinator {
return Coordinator(text: $text)
}
func makeUIView(context: UIViewRepresentableContext) -> UISearchBar {
let searchBar = UISearchBar()
searchBar.delegate = context.coordinator
searchBar.searchBarStyle = .default
searchBar.autocapitalizationType = .none
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext) {
uiView.text = text
}
}
result: