Search code examples
iosswiftswiftuixcode11

Navigation stuff in SwiftUI


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"))

    }
}

Solution

  • iOS 14

    You should use the toolbar modifier:

    .toolbar {
        ToolbarItem(placement: .navigationBarLeading) {
            Button("Cancel") { /* action */ }
        }
        ToolbarItem(placement: .navigationBarTrailing) {
            Button(action: { /* Actions */ }, label: {
                HStack {
                    Image(systemName: "trash")
                    Text("Delete")
                }
            })
            .foregroundColor(.red) // You can apply colors and other modifiers too
        }
    }
    

    Demo

    Note 1: You can have ANY View there. (not only a Button) and also any modifiers

    Note 2: Both codes above and below will generate the same look items but with different approachs


    iOS 13 and above (deprecated but still works)

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

    .navigationBarItems(
        leading: Button("Cancel") {
            // Actions
        },
        trailing: Button(action: {
            // Actions
        }, label: { Label("Delete", systemImage: "trash") }
        ).foregroundColor(.red) // You can apply colors and other modifiers too
    )
    

    💡 Pro TIP

    Always try to encapsulate each item in a separated struct, so your code will be simplified and very easy to replace with newer technologies. for example, take a look at this sample:

    .navigationBarItems(
          leading: MyCustomButtonItem(),
          trailing: MyCustomButtonItem(text: "foo", image: "Bard")
    )