I need to configure when the user clicks in the Search box to fulfill the condition (display another View). Once he clicks Cancel to display the original view (which can already be tested via .onChange(of: searchText) { value in if (!value.isEmpty) {...)
NavigationStack {
...
if showView == true {}
...
}
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: LocalizedStringKey("Look for something"))
.focused($focusState)
.onChange(of: focusState, perform: {
showView = true
})
When the user starts searching, I need to show a different View and hide the original one because I have search settings on the new one. As soon as he clicks on the Search button, the search starts.
@FocusState
isn't the way to handle this, as the search bar does update or respond to changes in this state.
What you need to use is the isSearching
Environment
variable in the view on which the .searchable
modifier is applied, for example:
struct ContentView: View {
@State private var searchText = ""
var body: some View {
NavigationView {
SearchingView(searchText: $searchText)
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: LocalizedStringKey("Look for something"))
}
}
}
struct SearchingView: View {
@Environment(\.isSearching) private var isSearching
@Binding var searchText: String
var body: some View {
if isSearching {
// Show your filtered data view
} else {
// Show non-searching view
}
}
}