how do i create a nav bar in swiftui

Asked on 08/03/2024

1 search

To create a navigation bar in SwiftUI, you can use the NavigationView and NavigationStack components. Here is a basic example of how to set up a navigation bar:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Hello, World!")
            }
            .navigationTitle("Home")
            .navigationBarItems(trailing: Button(action: {
                print("Button tapped")
            }) {
                Image(systemName: "plus")
            })
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example:

  • NavigationView is used to create a navigation context.
  • navigationTitle sets the title of the navigation bar.
  • navigationBarItems allows you to add items to the navigation bar, such as buttons.

For more advanced navigation and customization, you can explore the new features in SwiftUI introduced in iOS 18. For example, the session Elevate your tab and sidebar experience in iPadOS discusses updates to the tab bar and sidebar, which can be useful for creating more integrated navigation experiences.

If you want to dive deeper into SwiftUI essentials, you can check out the session SwiftUI essentials which covers built-in capabilities and more advanced topics.