How to hide and show the sidebar programmatically
About 2 min
How to hide and show the sidebar programmatically 관련
SwiftUI by Example
Back to Home
How to hide and show the sidebar programmatically | SwiftUI by Example
How to hide and show the sidebar programmatically
Updated for Xcode 15
When using NavigationSplitView
on macOS and iPadOS, SwiftUI lets us toggle showing the sidebar, content view, and detail view using the NavigationSplitViewVisibility
enum.
This code sample shows all three variations:
struct ContentView: View {
@State private var columnVisibility = NavigationSplitViewVisibility.detailOnly
var body: some View {
NavigationSplitView(columnVisibility: $columnVisibility) {
Text("Sidebar")
} content: {
Text("Content")
} detail: {
VStack {
Button("Detail Only") {
columnVisibility = .detailOnly
}
Button("Content and Detail") {
columnVisibility = .doubleColumn
}
Button("Show All") {
columnVisibility = .all
}
}
}
}
}
There are four modes to choose from:
- In
.detailOnly
mode, the detail view will take up all the available screen space for your app. - In
.doubleColumn
mode, you'll see both the content and detail views. - In
.all
mode, the system will attempt to show all three views if they exist. In the case where you don't have a content view (the middle view), it will only show two. - In
.automatic
mode, the system will do what it thinks is best based on the current device and orientation.
Note
providing the columnVisibility
is done using a binding because your value will automatically be updated as the user interacts with your UI.
Although SwiftUI uses different names for these three parts of our split view interface, they match up directly with UIKit counterparts: the sidebar is “primary” in UIKit, content is “supplementary”, and detail is “secondary”.
Similar solutions…
How to add a sidebar for iPadOS
SwiftUI tips and tricks | SwiftUI by Example
SwiftUI tips and tricks
All SwiftUI property wrappers explained and compared | SwiftUI by Example
All SwiftUI property wrappers explained and compared
How to hide and reveal content using DisclosureGroup | SwiftUI by Example
How to hide and reveal content using DisclosureGroup
How to hide and show the status bar | SwiftUI by Example
How to hide and show the status bar