Home > Back-end >  SwiftUI: Why toolbar items added from any view appear only in the main toolbar in macOS?
SwiftUI: Why toolbar items added from any view appear only in the main toolbar in macOS?

Time:12-18

In my macOS app (SwiftUI project multiplateform), I have a main toolbar that works well.

However, when I loaded a view, in a popover for example, the toolbar items set in the popover view, are added to the main toolbar.

In this image above, the X icon visible at top belongs to the popover view. It's added when loading the popover and hidden when leaving the popover.

1

The toolbar code in the popover view:

toolbar {
                Button(action: {
                    selectedItemId = nil // set
                },
                    label: { Image(systemName: "x.circle") })
            }

Adding a searchable field will also be added in the main toolbar, and can break completly the toolbar layout.

.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always)) {}

How macOS controls the different toolbar items from different views ? Each new view shoulb be a "window" to control a new toolbar attached to it ?

Thanks in advance.

CodePudding user response:

.popover does not support Toolbars.
And in a Sheet the toolbar items are placed at the bottom.

But you can always include your own controls and buttons in a Popover. Just don't use .toolbar:

struct ContentView: View {
    
    @State private var showSheet = false
    @State private var showPopover = false

    var body: some View {
        
        VStack {
            Button("Show sheet") { showSheet = true }
            Button("Show popover") { showPopover = true}
        }
        .toolbar {
            Button {
            } label: {
                Image(systemName: "house")
            }
        }
        
        .sheet(isPresented: $showSheet) {
            VStack {
                Text("Dummy Sheet")
                List(0..<20) { i in
                    Text("item \(i)")
                }
                .toolbar {
                    Button {
                    } label: {
                        Image(systemName: "x.circle")
                    }
                }
            }
            .padding()
            .frame(minWidth: 200, minHeight: 200)
        }
        
        .popover(isPresented: $showPopover) {
            VStack {
                Text("Dummy Popover")
                List(0..<20) { i in
                    Text("item \(i)")
                }
                Divider()
                Button {
                } label: {
                    Image(systemName: "x.circle")
                }
            }
            .frame(minWidth: 200, minHeight: 200)
            .padding(.vertical)
        }
    }
}
  • Related