macCatalyst/ SwiftUI Touch Bar

2020-07-20 03:25发布

问题:

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.

回答1:

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.