I am currently learning to create multiplatform applications using SwiftUI and NavigationSplitView
, and I faced the problem of arranging different Views in the same App.
Let's open the default Notes application, and here, we can see a switch between two and three-column views of the content.
So my question is, how to arrange this kind of view for different App pages using NavigationSplitView
?
- First page has two columns interface
- Second has three columns
From the way Apple made the NavigationSplitView
API, it is clear that having two and three column layouts shouldn't happen or should be avoided.
Nevertheless, you can still achieve this through the use of two split views wrapped in a condition. Something like this, which I have tested, will work:
struct ContentView: View {
@State private var selectedInt: Int? = 1
@State private var columnVisibility: NavigationSplitViewVisibility = .all
var sidebarList: some View {
List(1...10, id: \.self, selection: $selectedInt) { int in
NavigationLink("Row \(int)", value: int)
}
.navigationTitle("Sidebar")
}
var contentView: some View {
Text("Content \(selectedInt ?? 0)")
}
var detailView: some View {
Text("Detail \(selectedInt ?? 0)")
}
var body: some View {
Group {
// Only rows that are a multiple of 2 will have a two-column layout
if selectedInt?.isMultiple(of: 2) == true {
NavigationSplitView(columnVisibility: $columnVisibility) {
sidebarList
} detail: {
detailView
}
} else {
NavigationSplitView(columnVisibility: $columnVisibility) {
sidebarList
} content: {
contentView
} detail: {
detailView
}
}
}
.navigationSplitViewStyle(.balanced)
}
}
I don't know, however, what impact this has on performance or rendering, if any.