How can I add a navigation split view

Asked on 08/02/2024

1 search

To add a navigation split view in SwiftUI, you can use the existing NavigationSplitView APIs. Here are some steps and tips based on the content from WWDC:

  1. Using NavigationSplitView:

    • You can build a navigation split view using the NavigationSplitView API. This is particularly useful for creating sidebars that help users navigate through your app's content.
  2. Adopting Sidebar Appearance:

    • If you are currently using a tab bar, you can easily switch to a sidebar appearance by setting the tab view style to sidebarAdaptable. This can be done with just one line of code:
      .tabViewStyle(.sidebarAdaptable)
      
    • This modifier will transform your tab bar into a sidebar, which is especially useful on iPadOS and tvOS.
  3. Customization and Flexibility:

    • The sidebar in iOS 18 and iPadOS 18 has become more flexible, allowing users to switch between a tab bar and a sidebar representation. This can be particularly useful for apps with a lot of content, as it allows for customization such as reordering and removing tabs programmatically.
  4. Example Code:

    • Here is a simple example of how you might set up a navigation split view in SwiftUI:
      import SwiftUI
      
      struct ContentView: View {
          var body: some View {
              NavigationSplitView {
                  List {
                      NavigationLink("Item 1", destination: Text("Detail 1"))
                      NavigationLink("Item 2", destination: Text("Detail 2"))
                  }
                  .navigationTitle("Sidebar")
              } detail: {
                  Text("Select an item")
              }
          }
      }
      
      struct ContentView_Previews: PreviewProvider {
          static var previews: some View {
              ContentView()
          }
      }
      

For more detailed information, you can refer to the session Elevate your tab and sidebar experience in iPadOS (06:41).

Relevant Sessions

  1. Elevate your tab and sidebar experience in iPadOS
  2. What’s new in SwiftUI
  3. Migrate your TVML app to SwiftUI

These sessions provide comprehensive insights into using and customizing navigation split views and sidebars in SwiftUI.