2

I am creating an app and I am using .searchable for my home view, but once it is clicked, I want it to bring up a new view where results of what is being searched is shown, and once the cancel button is clicked goes back to the home view.

I currently have .searchable(text: $searchText) and it is showing the search bar, and I have tried .overlay{SearchView()} but it is just putting it over the home view. Is there a way to do this.

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160

1 Answers1

0

You need to use the @Environment variable isSearching to determine which view to display, e.g.

struct ContentView: View {

    @State private var searchText = ""

    var body: some View {
        NavigationView {
            SearchingView(searchText: $searchText)
                .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search")
                .navigationTitle("Title")
        }
    }
}


struct SearchingView: View {
    @Environment(\.isSearching) private var isSearching
    @Binding var searchText: String
    
    var body: some View {
        if isSearching {
            List("This is displayed when searching".components(separatedBy: " "), id: \.self) { word in
                Text(word )
            }
            .listStyle(.plain)
        } else {
            Text("Here is the normal view")
        }
    }
}

enter image description here

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160