Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

macos - How to get a sidebar open state in Swift?

I have a SwiftUI app with a sidebar (NavigationView) I'm able to toggle the sidebar via hotkeys using SidebarCommands() and programmatically via the following function:

func toggleSidebar() {
  NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}

I have this attached to a button action, but I want to highlight the button in a different color when sidebar is open.

How can I get the state of the sidebar?

question from:https://stackoverflow.com/questions/65857810/how-to-get-a-sidebar-open-state-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Half of a solution: (reason it's half see bottom)


Assuming you have a ToolbarItem:

ToolbarItem {
    Button(
        action: toggleSidebar, 
        label: { Label("Sidebar", systemImage: "sidebar.left") }
    )
}

You could add a Bool value in your view @State private var sidebarOpened: Bool = true

Then you can toggle that value with the same button:

ToolbarItem {
    Button(
        action: {
            toggleSidebar()
            sidebarOpened.toggle()
        }
        label: { Label("Sidebar", systemImage: "sidebar.left") }
    )
}

Now you can set the color of your label based on sidebarOpened:

label: { Label("Sidebar", systemImage: "sidebar.left") }
.foregroundColor(sidebarOpened ? .red : .secondary)

Note:

This method doesn't really know if the sidebar is open or not, instead it works based on if the button was clicked, so it gives you different result if you left the sidebar opened or not the last time you closed the app.

It would be better to have a value of whether the sidebar is open or not, which I don't think there's a native SwfitUI solution yet. Probably need to check AppKit NSSplitView.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...