I watched the WWDC video "Adopt the new look of macOS" where they introduced NSSearchToolBarItem in Swift at 11:32 in the video.
This is exactly what I need to do but how do I add this search to my toolbar in SwiftUI?
There are lots of complex examples but they all seem to be written before this new API. There must be a simpler way?
import SwiftUI
var listItems = ["Item 1", "Item 2", "Item 3", "Item 4"]
struct ContentView: View
{
@State var select: String? = "Item 1"
@State var searchText: String = "hello"
var body: some View
{
VStack
{
NavigationView
{
List
{
ForEach((0..<listItems.count), id: \.self)
{index in
Label(listItems[index], systemImage: "briefcase")
}
}
}
.toolbar
{
Button(action: {})
{
Label("Upload", systemImage: "square.and.pencil")
}
TextField("Search", text: $searchText)
}
}
}
}
There doesn't look to be an obvious way to do this using
NSSearchToolbarItem
directly but, looking into that class, it's using anNSSearchField
under the hood which is relatively easy to use in SwiftUI usingNSViewRepresentable
:You can then use this hosted view directly inside a
ToolbarItem
:You may wish to fiddle with the dimensions a little (in the
.frame()
call) to match the exit platform-native dimensions but this seems to match pretty closely how Notes.app looks.Search toolbar item in Notes.app:
Search toolbar item from the example code above: