xcodemacosswiftuinstouchbar

How can I use NSTouchBar in SwiftUI MacOS App?


I am trying to add TouchBar support for my MacOS app in SwiftUI.

I found that I have to call ..

  NSApp.isAutomaticCustomizeTouchBarMenuItemEnabled = true

.. in my AppDelegate. But what is now the best way to create the TouchBar? Can I add it inside the Storyboard of the menu of my Mac app or do I need to create it programmatically?

When I follow Apple documentation I get to this point:

You create a Touch Bar by adding one to a view controller in the storyboard, or by creating one programmatically by overriding NSResponder's makeTouchBar() function.

Is it possible to create an own NSViewController and then embed it in NSNiewController representable?

Maybe anyone has a good advice how I can support TouchBar in SwiftUI.


Solution

  • The simplest is just use specific identifier for the view whenever applicable by your logic, like in below example

    struct ContentView: View {
      var body: some View {
         SomeView()      // << your view here 
            .touchBar {
                Button("Do") {
                   // .. Do something here
                }
            }
      }
    }
    

    so when view appeared the related Touch Bar button appears as well.

    For more complicated cases you can see at TouchBar and corresponding extension

    extension View {
    
        /// Sets the `TouchBar` to be shown in the Touch Bar when applicable.
        @available(iOS, unavailable)
        @available(tvOS, unavailable)
        @available(watchOS, unavailable)
        public func touchBar<Content>(_ touchBar: TouchBar<Content>) -> some View where Content : View
    
        /// Sets the `TouchBar` content to be shown in the Touch Bar when applicable.
        @available(iOS, unavailable)
        @available(tvOS, unavailable)
        @available(watchOS, unavailable)
        public func touchBar<Content>(@ViewBuilder content: () -> Content) -> some View where Content : View
    }