如果你正在學 SwiftUI Toolbar,Phil Zakharchenko 的〈A Tale of Adopting Customizable SwiftUI Toolbars〉是一篇值得讀的文章。

文章把 SwiftUI 的普通 toolbar 與 customizable toolbar 分得很清楚。對 customizable toolbar 來說,每個可自訂控制項都應該有自己的 ToolbarItem(id:),不同的邏輯區域再用 ToolbarSpacer 分隔。

這套結構到了 macOS 27 出現問題。

macOS 27 重新決定了 Toolbar grouping

SwiftChat 的 toolbar 原本需要三個區域:

  1. Sidebar 與 New chat。
  2. Conversation source。
  3. Share 與 Open in New Window。

第一與第二區都位於 navigation placement,中間已經加入 fixed ToolbarSpacer。但在 macOS 27 實際執行時,系統仍把它們視為同一個 navigation island。

ToolbarSpacer 存在於 toolbar 結構中,卻無法阻止系統重新 grouping。Conversation source 因此被合併到 Sidebar 與 New chat 的 capsule 裡。

macos-27-toolbar-auto-grouping-example.png

這不是 spacing 數值能修正的版面問題。Toolbar 的分組已由系統決定。

Workaround:macOS 改由 AppKit 接管 Toolbar

目前的 workaround 是保留 SwiftUI 管理的狀態與 actions,但不再讓 SwiftUI 生成 macOS toolbar 的結構。

macOS 分支使用 SwiftUI Introspect 取得 NSWindow,再把 window.toolbar 替換成由 AppKit 建立的 NSToolbar。其他平台則繼續使用原本的 SwiftUI ToolbarContent。

分開 macOS 與其他平台

extension View {
    @ViewBuilder
    func conversationToolbar(
        sidebarVisibility: Binding<NavigationSplitViewVisibility>,
        surface: Binding<ChatSurfaceKind>,
        subtitle: String,
        newConversation: @escaping () -> Void,
        shareURL: URL?,
        openConversationInNewWindow: @escaping () -> Void
    ) -> some View {
        #if os(macOS)
        configureConversationToolbar(
            sidebarVisibility: sidebarVisibility,
            surface: surface,
            subtitle: subtitle,
            newConversation: newConversation,
            shareURL: shareURL,
            openConversationInNewWindow: openConversationInNewWindow
        )
        #else
        toolbar {
            ConversationToolbar(
                sidebarVisibility: sidebarVisibility,
                surface: surface,
                subtitle: subtitle,
                newConversation: newConversation,
                shareURL: shareURL,
                openConversationInNewWindow: openConversationInNewWindow
            )
        }
        #endif
    }
}

AppShellView 不再直接使用 .toolbar {},而是改用這個跨平台入口:

.conversationToolbar(
    sidebarVisibility: $navigation.sidebarVisibility,
    surface: $navigation.selectedSurface,
    subtitle: conversationSubtitle,
    newConversation: presentNewConversation,
    shareURL: shareableChatGPTConversationURL,
    openConversationInNewWindow: openConversationInNewWindow
)

取得 NSWindow