< How to create a two-column or three-column layout with NavigationSplitView | How to customize a view’s width in NavigationSplitView > |
Updated for Xcode 14.2
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
}
}
}
}
}
Download this as an Xcode project
There are four modes to choose from:
.detailOnly
mode, the detail view will take up all the available screen space for your app. .doubleColumn
mode, you’ll see both the content and detail views..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..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”.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.