search bar in toolbar in SwiftUI Xcode 12 for macOS App

Viewed 986

In the newest iteration of Xcode (12) there is now a toolbar per default at the top of an App.

I like the design but I did not really understand how to use it yet. It seems to work differently than normal views. enter image description here Right now I want to add a search bar to it that covers in a adaptive layout all the space it can. But this does not seem to work. At least not like in a normal View. (I have to add that I am not the most experienced yet when it comes to SwiftUI).

This is how my search bar looks right now (tiny blue thing on the right next to the Buttons that only expands when I type in it):

And this is the respective code of the toolbar in my main View:

var body: some View {
        List {
            ForEach(items) { item in
                if !installedOnly || item.installed {
                    Text("\(item.name!)")
                        .foregroundColor(item.installed && !installedOnly ? .green : .white)
                }
            }
            .onDelete(perform: deleteItems)
        }
        .toolbar {
            HStack{
                TextField("", text: $search_term)
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                Button(action: togglePinned) {
                    Label("Add Item", systemImage: installedOnly ? "pin.fill" : "pin")
                }
                Button(action: getApps) {
                    Label("Add Item", systemImage: "arrow.clockwise")
                }
            }
        }
    }

Any feedback is much appreciated!

1 Answers

Don't use a HStack for the toolbar content. Every view in the toolbar is a item.

.toolbar {
     TextField("", text: $search_term)
         .textFieldStyle(RoundedBorderTextFieldStyle())
         .frame(minWidth: 200)
     Button(action: togglePinned) {
         Label("Add Item", systemImage: installedOnly ? "pin.fill" : "pin")
     }
     Button(action: getApps) {
         Label("Add Item", systemImage: "arrow.clockwise")
     }
}
Related