Search code examples
macosswiftuimacos-catalina

How do I add a toolbar to a macOS app using SwiftUI?


I am trying to add a toolbar inside the title bar to a macOS app using SwiftUI, something similar to what is shown below.

Toolbar in the titlebar in macOS app

I am unable to figure out a way to achieve this using SwiftUI. Currently, I have my toolbar (which just has a text field) inside my view, but I want to move it into the title bar.

My current code:

struct TestView: View {
    var body: some View {
        VStack {
            TextField("Placeholder", text: .constant("")).padding()
            Spacer()
        }
    }
}

So, in my case, I need to have the textfield inside the toolbar.


Solution

  • As of macOS 11 you’ll likely want to use the new API as documented in WWDC Session 10104 as the new standard. Explicit code examples were provided in WWDC Session 10041 at the 12min mark.

    NSWindowToolbarStyle.unified
    

    or

    NSWindowToolbarStyle.unifiedCompact
    

    And in SwiftUI you can use the new .toolbar { } builder.

    struct ContentView: View {
    
    
      var body: some View {
            List {
                Text("Book List")
            }
            .toolbar {
                Button(action: recordProgress) {
                    Label("Record Progress", systemImage: "book.circle")
                }
            }
        }
    
        private func recordProgress() {}
    }