Peter Lapisu
Peter Lapisu

Reputation: 21005

SwiftUI macOS place toolbar item to the rightmost position when dispaying a search bar

Since macOS 13, the primaryAction no longer displays next on left to the search bar

enter image description here

    MainView()
    .toolbar {
        ToolbarItem {
            Spacer()
        }
        ToolbarItemGroup(placement: .status) {
            Text("Status")
        }
        ToolbarItemGroup(placement: .principal) {
            Text("Principal")
        }
        ToolbarItemGroup(placement: .primaryAction) {
            Text("Primary")
        }
        ToolbarItemGroup(placement: .keyboard) {
            Text("Keyboard")
        }
        ToolbarItemGroup(placement: .secondaryAction) {
            Text("Secondary")
        }
        ToolbarItem {
            Text("Noplacement")
        }
    }
    .searchable(text: .constant(""))

how to position a toolbar item the topmost right next to search?

Note: without the search bar, they are put correctly to rightmost position

Upvotes: 4

Views: 2380

Answers (2)

MrAsterisco
MrAsterisco

Reputation: 888

On macOS Sonoma, adding a ToolbarItem with just a Spacer inside creates the "Flexible Space" item which it's normally used in macOS toolbars to align elements.

With this, there's no need to provide a value for placement, as you will be able to place elements in any position.

ToolbarItem(
  id: "flexible-space-id" // Provide a ID to allow for toolbar customization
) {
  Spacer()
}

Customizable toolbar with flexible space items

Upvotes: 2

Max G
Max G

Reputation: 11

You simply need to add a Spacer()

   .toolbar {     
     ToolbarItemGroup(placement: .primaryAction) {
                            Spacer()
                            Text("Primary")
                        }
   }
   .searchable(text: .constant(""))

Here's what it looks like

Upvotes: -1

Related Questions