簡體   English   中英

如何使用 SwiftUI 顯示觸控欄按鈕?

[英]How can I display Touch Bar Buttons using SwiftUI?

我正在嘗試為SwiftUI View添加 Touch Bar 支持。 SwiftUI使用.touchBar(content: () -> View)函數似乎有SwiftUI API,但文檔不存在,我無法讓我的 Touch Bar 顯示任何內容。

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .touchBar {
                Button(action: {

                }) {
                    Text("do something")
                }
        }
    }
}

這段代碼可以編譯並運行,但 Touch Bar 仍然是空的。 如何讓我的觸摸欄使用 SwiftUI(不是催化劑)顯示內容?

如果沒有在System Preferences -> Keyboard -> Shortcuts選中“使用鍵盤導航在控件之間移動焦點”,則使用.focusable不起作用。 為了解決這個問題,我這樣做了:

/// Bit of a hack to enable touch bar support.
class FocusNSView: NSView {
    override var acceptsFirstResponder: Bool {
        return true
    }
}

/// Gets the keyboard focus if nothing else is focused.
struct FocusView: NSViewRepresentable {

    func makeNSView(context: NSViewRepresentableContext<FocusView>) -> FocusNSView {
        return FocusNSView()
    }

    func updateNSView(_ nsView: FocusNSView, context: Context) {

        // Delay making the view the first responder to avoid SwiftUI errors.
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            if let window = nsView.window {

                // Only set the focus if nothing else is focused.
                if let _ = window.firstResponder as? NSWindow {
                    window.makeFirstResponder(nsView)
                }
            }
        }
    }
}

來自如何使用帶有 NSWindow 的 SwiftUI 觸摸欄的幫助- Apple 開發者論壇

使用 focusable() 修飾符

當您在.touchBar(content:)修飾符之前添加.focusable()修飾符時,觸摸欄會顯示文本。

struct ContentView: View {

    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .focusable()
            .touchBar {
                Button(action: {
                    print("Perform some action")
                }) {
                    Text("do something")
                }
        }
    }
}

觸控欄圖片

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM