8

how could I add Touch Bar Support in Catalyst- Apps written in SwiftUI?

For Example, if I want to display a Button in a View:

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack{
        #if targetEnvironment(macCatalyst)
            Text("macOS")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .focusable()
            .touchBar {
                Button(action: {
                    print("tapped")
                }) {
                    Text("TestButton")
                }
            }
        #endif
        Text("iOS")
        }
    }
}

If I use it in a an macOS App it works but if I use it in Catalyst and add targetEnvironment it occurs the error:

'focusable(_:onFocusChange:)' is unavailable in iOS and 'touchBar(content:)' is unavailable in iOS

Thank you for help.

TS251
  • 353
  • 4
  • 10

2 Answers2

1

You can add custom view modifier:

struct TouchBarView: ViewModifier {
    func body(content: Content) -> some View {
        #if os(macOS)
        return content
                .touchBar { ... }
        #else
        return content
        #endif
    }
}

Usage:

Text("Text")
    .modifier(TouchBarView())
Sound Blaster
  • 4,778
  • 1
  • 24
  • 32
0

Change

#if targetEnvironment(macCatalyst)

to

#if os(macOS)

macCatalyst must still be in the environment for iOS Mac Catalyst apps, so manually checking the OS should be reliable.

Benj
  • 736
  • 7
  • 21