Home > other >  How to create `Toolbar` with left, center, and right components in Swift for macOS?
How to create `Toolbar` with left, center, and right components in Swift for macOS?

Time:01-31

I'm writing a music app for macOS in SwiftUI, and hope its toolbar behave like this: Artwork with title at left, play controls at center, and inspector toggles at right, as shown below. However, it seems that they cannot be laid correctly at the same time.

enter image description here

So, I write a small demo to reproduce my problem here.

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .toolbar {
                ToolbarItem(placement: .navigation) {
                    Button("Left") { }
                }
                ToolbarItem(placement: .principal) {
                    Button("Center") { }
                }
                ToolbarItem(placement: .primaryAction) {
                    Button("Right") { }
            }
        }
    }
}

The right button is displayed at wrong placement. But if I delete left and center button, the right button will correctly appear at right of window as expected.

How can I fix this, and display components at left, center, and right at the same time?

enter image description here

CodePudding user response:

You can add a ToolbarItem that contains only a Spacer

.toolbar {
    ToolbarItem(placement: .navigation) {
        Button("Left") { }
    }
    ToolbarItem(placement: .principal) {
        Button("Center") { }
    }
    ToolbarItem {
        Spacer()
    }
    ToolbarItem(placement: .primaryAction) {
        Button("Right") { }
    }
}
  • Related