🫣

[SwiftUI/MacOS]サイドバーの表示・非表示ボタンを明示的に作成する

2025/01/12に公開

作業メモです。

TL;DR

  • Buttonのaction:にNSApp.sendAction(#selector(NSSplitViewController.toggleSidebar(_:)), to: nil, from: nil)を追加するだけ
  • メニューバーに「ツールバーの表示・非表示する」メニューアイテムを表示するには、WindowGroup.commandsコンテンツにSidebarCommands()を追加する

Abstract

This article will summarize how to mitigate this problem by adding other options to toggle the sidebar. This article describes two ways to tackle this problem. Option 1 is to add Toggle Sidebar menu option add the desire command to a .command modifier with SidebarCommands(). The other option is to add a button to a toolbar that calls the toggleSidebar method.

各種バージョン

  • XCode 16.2
  • MacOS minimum development version: 14.0
  • Swift 5

やりたいこと

  • NavigationStackNavigationViewでツールバーを作成したときに、ツールバーを表示するボタン[下図]を明示的に表示したい。(NavigationLinkで画面遷移したときなどシステム的に自動で表示されないときがある)

成果物

ソースコード

import SwiftUI

struct MainView: View {    
    // MainView
    var body: some View {
        NavigationStack() {
            // Navigation area
            Text("Navigation area")
                .toolbar {
                    ToolbarItem(placement: .navigation) {
                        Button(action: toggleSidebar, label: { 
                            Image(systemName: "sidebar.leading")
                        })
                    }
                } 
            // Body area
            Text("Body area")
            // abbr.
        }  
    }

    private func toggleSidebar() {
#if os(macOS)
        NSApp.sendAction(#selector(NSSplitViewController.toggleSidebar(_:)), to: nil, from: nil)
#endif
    }
}

メニューアイテムに追加する

SidebarCommands()を追加するだけ。

@main
struct SampleApp: App {
    var body: some Scene {
        WindowGroup {
            MainView()
        }
        .commands {
            SidebarCommands()
        }
    }
}

参考リンク

Discussion