Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
Bijoy Thangaraj Avatar asked Feb 29 '20 12:02

Bijoy Thangaraj


People also ask

How do I use SwiftUI toolbar?

Toolbar items in the bottom bar As we can see in the example, SwiftUI provides the toolbar modifier that we can use to add toolbar items. A ToolbarItem has two required parameters. The first one is the placement and the second one is a closure to build the view that represents our action. Toolbar items in bottom bar.

Can you build macOS apps with Swift?

Set the interface to SwiftUI, the life cycle to SwiftUI App, and the language to Swift, and then click Finish. Set the scheme to MacLandmarks > My Mac. By setting the scheme to My Mac, you can preview, build, and run the macOS app.

Does SwiftUI work on Mac?

SwiftUI runs on iOS 13, macOS 10.15, tvOS 13, and watchOS 6, or any future later versions of those platforms.


1 Answers

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() {}
}
like image 68
mcritz Avatar answered Sep 27 '22 19:09

mcritz