create a view with a search bar under a piece of text in swiftui in swift

To create a searchable view in SwiftUI, you can use a combination of NavigationView, List, and SearchBar. Here's an example code snippet:

main.swift
struct ContentView: View {
    @State private var searchText = ""

    var body: some View {
        NavigationView {
            VStack {
                Text("Searchable List")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                SearchBar(text: $searchText)
                List {
                    ForEach((1...20).filter {
                        self.searchText.isEmpty ? true : "\($0)".contains(self.searchText)
                    }, id: \.self) {
                        Text("\($0)")
                    }
                }
            }
            .navigationBarTitle(Text("SwiftUI Search Bar"))
        }
    }
}

struct SearchBar: UIViewRepresentable {
    @Binding var text: String

    class Coordinator: NSObject, UISearchBarDelegate {
        @Binding var text: String

        init(text: Binding<String>) {
            _text = text
        }

        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            text = searchText
        }

        func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
            searchBar.resignFirstResponder()
        }
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(text: $text)
    }

    func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
        let searchBar = UISearchBar(frame: .zero)
        searchBar.delegate = context.coordinator
        return searchBar
    }

    func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
        uiView.text = text
    }
}
1600 chars
57 lines

In this example, the SearchBar component is created as a separate UIViewRepresentable struct that conforms to the UISearchBarDelegate protocol. It includes a Coordinator class that handles the delegate functions for the search bar.

The search bar is then added to the top of the VStack, and the List component is filtered by the $searchText binding.

Note that the List component uses the filter function to return the array of integers that should be displayed based on whether the search text is empty or not.

This should result in a display that looks something like this:

SwiftUI searchable list screenshot

gistlibby LogSnag