xcodemacosswiftuinavigationsplitview

How to implement Finder like searchbar in SwiftUI?


It's easy to show a search bar using NavigationSplitView and .searchable on macOS app titlebar. But I have no idea to custom the search bar.

My question is:

How to use NavigationSplitView and searchable to implement a search icon and search bar similar to Finder? The default search box is hidden, when the search icon is clicked, the search box will expand with animation, and the search icon is hidden.

search bar showing

search bar hidden


Solution

  • searchable already has the same behaviour as the search feature in Finder.

    The difference is that in Finder, there are many other toolbar buttons, but in your app, the toolbar probably has nothing but the search text field.

    Since there are many other toolbar buttons in Finder, the search text field collapses to just a magnifying glass button, in order to show as many toolbar buttons as possible. When there is more space, the search text field will appear normally, just like in your app.

    Try resizing the Finder window to increase its width. There will be a point where the search text field is displayed normally, and you cannot collapse it.

    enter image description here

    You can put some random junk in the toolbar to force the search bar to collapse.

    .toolbar {
        ToolbarItem {
            Text(String(repeating: " ", count: 100))
        }
    }
    

    but just like in Finder, there will always be a window width where the search text field can be displayed in full.