Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NavigationStack Searchable .focused

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.

like image 390
Aleš Slabý Avatar asked Sep 02 '25 10:09

Aleš Slabý


2 Answers

@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
        }
    }
}
like image 123
Ashley Mills Avatar answered Sep 04 '25 10:09

Ashley Mills


With Xcode 16 and from iOS 18 / macOS 15

You can use the searchFocused modifier and bind a simple @FocusState variable to it like:

@FocusState private var isSearchFieldFocused: Bool

var body: some View {
   NavigationSplitView { ... }
      .searchable(text: $searchText, isPresented: $isPresented)
      .searchFocused($focusState) // 👈 Like this here
}
like image 39
Mojtaba Hosseini Avatar answered Sep 04 '25 12:09

Mojtaba Hosseini