Home > Back-end >  Is there any way to control the width of the search field as it's being added to the toolbar wh
Is there any way to control the width of the search field as it's being added to the toolbar wh

Time:02-17

I'm using SwiftUI to code a macOS app, and I'm adding a .searchable to it, placing the search field on the toolbar. macOS is adding it to the end of the toolbar, which is good. However, it's too wide.

The code is simple

.searchable(
        text: $searchText,
        placement: .toolbar,
        prompt: "Search..."
)

Is there any way to control the width of the search field as it's being added to the toolbar?

Furthermore, is there a way to set it to always display as "minimized" the way some of the macOS apps do?

This is the way it looks on my app:

enter image description here

And this is what it looks like on one of the macOS apps: just a magnifying glass.

enter image description here

CodePudding user response:

The search field resizes itself automatically and its appearance depends on the situation. If you have a resizable window and drag it smaller, you will end up in the appearance you describe.

Also if you add more elements or functions to the toolbar, the search field will eventually collapse to the magnifying glass only.

You could use this to add an empty but very wide Button field to the toolbar to "push" the search field to the side:

        .toolbar {
            ToolbarItemGroup {
                Button("") {}
                .frame(width: 400)
                .buttonStyle(.plain)
            }
        }
  • Related