Search code examples
swiftmacosswiftui

How can I place a toolbar item to the right of .searchable?


I am trying to use a button in my toolbar to toggle an inspector and I also have a .searchable to filter a list. This is how it currently looks:

Screenshot

Is there any way I can move the button for the inspector to the right of the search bar?

struct ContentView: View {
    @State private var searchText = ""
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .padding()
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button("Inspector", systemImage: "sidebar.right") { }
            }
        }
        .searchable(text: $searchText)
    }
}

Solution

  • The current behavior for .searchable in SwiftUI is to always put it as the right most item in the toolbar: Searchable Docs. You Can put it into a side bar if you have a detail view in a navigation.

    I think the only way to do this with swiftUI is to make your own custom ToolBar item with a TextField for searching.

    Here's an example:

    ... // Add button ToolbarItem
    ToolbarItem{
        HStack{
            Image(systemName: "magnifyingglass")
            TextField("Search", text: $searchText)
                .onChange(of: searchText) { print("Your text updated to: \($searchText)")
                }
                .frame(width: 150)
        }
    }
    
    ... // Detail button ToolbarItem
    

    macOS toolbar