9

I'm trying to hide Search bar in my app like Apple did in their messages app:

enter image description here

I've already implemented UISearchBar in SwiftUI:

struct SearchBar: UIViewRepresentable {
@Binding var text: String

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

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

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

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

func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
    let searchBar = UISearchBar(frame: .zero)
    searchBar.delegate = context.coordinator
    searchBar.searchBarStyle = .minimal
    searchBar.placeholder = "Поиск по названию, дедлайну или описанию"
    return searchBar
}

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

How can I implement hide and hiding animation in SwiftUI?

alexandrov
  • 363
  • 3
  • 11

1 Answers1

1

SwiftUI 3.0 (iOS 15.0+)

Apple made it possible in very native way.

You just need to use .searchable() modifier with view you want to make searchable and ensure that you have NavigationView as parent of your views.

Example

struct CountriesView: View {
    let countries = ["United States", "India", "Ukraine", "Russia", "Sweden"]
    @State var search: String = ""

    var body: some View {
        NavigationView {
            List(countries.filter({
                // we filter our country list by checking whether country name
                // does contain search string or not
                $0.lowercased().contains(search.lowercased()) 
           })) { country in
                Text(country)
            }.searchable(text: $search)
        }
    }
}

By the way, you can use computed properties to filter your array in more convenient way.

Then, the computed property for the filter from the example will be:

var searchResults: [String] {
   return countries.filter({$0.lowercased().contains(search.lowercased())})
}

So, List will look like this:

List(searchResults) {
    // ...
}

p.s. you can learn more about computed variables & properties in this swift.org article

alexandrov
  • 363
  • 3
  • 11