2

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.

  • 2
    As this is currently written it is unclear to me what you want to achieve. Please try to create a [mre] and elaborate more on what you want to achieve. Also reading [ask] may help you improve the question. – burnsi Jan 16 '23 at 18:07

1 Answers1

3

@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
        }
    }
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • 1
    Thank you. However isSearching is true throughout the search. But I'd like to somehow catch when the focus is just in the search box (I need this to show filtering when searching). Is there any way to do this? – Aleš Slabý Jan 23 '23 at 08:58
  • I'm not quite sure what you mean. When the cursor is in the search box (so it has focus) `isSearching` is true, so you should show your filtered data view. Otherwise show your normal view. I updated my answer to make that clearer. – Ashley Mills Jan 23 '23 at 09:04
  • @AlešSlabý isSearching is controlled by SwiftUI so we do not have to manually handle it. When the user first taps or clicks in a search field, the isSearching property becomes true. See - https://developer.apple.com/documentation/swiftui/environmentvalues/issearching – tayo Jul 05 '23 at 11:00