1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Posted at

作業メモです。

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

参考リンク

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?