首页 > 解决方案 > macCatalyst/ SwiftUI 触控栏

问题描述

如何在用 SwiftUI 编写的 Catalyst- 应用程序中添加触控栏支持?

例如,如果我想在视图中显示一个按钮:

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")
        }
    }
}

如果我在 macOS 应用程序中使用它,它可以工作,但如果我在 Catalyst 中使用它并添加 targetEnvironment,则会出现错误:

'focusable(_:onFocusChange:)' 在 iOS 中不可用,而 'touchBar(content:)' 在 iOS 中不可用

谢谢你的帮助。

标签: swiftuimac-catalystmacbookpro-touch-bar

解决方案


您可以添加自定义视图修饰符:

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

用法:

Text("Text")
    .modifier(TouchBarView())

推荐阅读