How do I do multiple toolbars at the top of a window in SwiftUI on MacOS

86 views Asked by At

I have something like this and both toolbars are on the same line. I want them both stacked on top of each other. One toolbar on top of the other:

struct ToolbarView: View {
    @ObservedObject var dm: DrawModel
    init( _ dm: DrawModel ) { self.dm = dm }
    
    var body: some View {
        VStack{ }
        .toolbar
        {   
            AddToolbarItems( dm, toolbar1 )
        }   

        .toolbar {
            AddToolbarItems( dm,  toolbar2 )
        }
    }
}

To be clearer the toolbar buttons are showing up like this. Where TB is a toolbar and the 2.1 is Toolbar 2 item 1. etc

TB2.1   TB2.2  TB1.1   TB1.2

Like this instead:

TB1.1   TB1.2
TB2.1   TB2.2

Edit-1

My output from WorkingDog's Suggestion

1

There are 1 answers

12
workingdog support Ukraine On

how about you try AddToolbarItems( dm, toolbar2 ) first followed by AddToolbarItems( dm, toolbar1 ), to give you what you like this instead: TB1.1 TB1.2 TB2.1 TB2.2.

VStack{ }
.toolbar {
    AddToolbarItems( dm, toolbar2 )
}
.toolbar {
    AddToolbarItems( dm,  toolbar1 )
}

Alternatively:

 .toolbar {
     AddToolbarItems( dm, toolbar1 )
     AddToolbarItems( dm, toolbar2 )
 }

EDIT-1:

If you have only the four items mentioned, then to display 2 sets of 2 items, you could try this:

 .toolbar {
     VStack(spacing: 1) {
         HStack(spacing: 1) {
            AddToolbarItems( dm, toolbar1 )
         }
         HStack(spacing: 1) {
            AddToolbarItems( dm, toolbar2 )
         }
     }
 }

Better still, have the HStack in your AddToolbarItems.

However, if you have many items, there may not be enough space for all of them. Note, the height of the .toolbar is determined by the system and cannot be changed. You can of course create your own custom toolbar, without using the .toolbar modifier, very easy to do and you can choose whatever size you want.

EDIT-2

Here is my full test code that works for me.

struct ContentView: View {
    var body: some View {
        ToolbarView()
    }
}

struct ToolbarView: View {
//    @ObservedObject var dm: DrawModel
    // no need for init()
    
    var body: some View {
        VStack {}
            .toolbar {
                VStack(spacing: 1) {
                    AddToolbarItems( ["TB1.1", "TB1.2"] )
                    AddToolbarItems( ["TB2.1", "TB2.2"] )
                }
            }
    }

    @ViewBuilder
    func AddToolbarItems(_ arr: [String]) -> some View {
        HStack (spacing: 1) {
            ForEach(arr, id: \.self) { item in
                Button(item){ }//.buttonStyle(.bordered)
            }
        }
    }
}

Here is a screen shot when using my code with Button and systemImage.

enter image description here