Navigation stuff in SwiftUI

Yuto picture Yuto · Jun 15, 2019 · Viewed 11.4k times · Source

I'm trying to figure out how to use the navigation bar in SwiftUI

I want to put BarButtonItem and images inside the NavigationBar

I have been able to display the navigation bar and put titles enter image description here

var body: some View {
    NavigationView{
        List(0...5) { note in

            VStack(alignment: .leading) {
                Text("title")
                Text("Date")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }

        }
        .navigationBarTitle(Text("Notes"))

    }
}

Answer

Mojtaba Hosseini picture Mojtaba Hosseini · Jun 15, 2019

You should use .navigationBarItems() modifier. For example you can add Button or Image like this:

.navigationBarItems(
    leading: Button("Title") {
         // Actions
    },

    trailing: Button(action: {
    // Actions
    }, label: { Image("Icon") })
)

Note:

You can have ANY View there. (not only a Button)

TIP

You can encapsulate each item in a struct:

struct NavigationButtonItem: View {
    var body: some View {
        Button("Title") {
           // Actions
        }
    }
}

struct NavigationImageItem: View {
    var body: some View {
        Button(action: {
            // Actions
        }, label: { Image("Icon") })
    }
}

And the use them like this:

.navigationBarItems(
      leading: NavigationButtonItem(),
      trailing: NavigationImageItem()
)