SwiftUI – How to create a Navigation Bar with custom items

Share on facebook
Share on twitter
Share on pinterest

Customizing the navigation bar in SwiftUI by inserting bar items is so easy, here’s how to do it! 👇

Step 1: Make sure your whole view is wrapped into a navigation view.

Step 2: Add a navigation bar title to your navigation view. With this modifier, you can also decide if you want a large or a default navigation bar (displayMode).

Step 3: Now you can add the navigationBarItems modifier! The leading parameter takes in all items that should get displayed on the “left side”, the trailing parameter the ones for the” right side”. If you want more than one item for each side, you can wrap the parameters input into an HStack. In this HStack you can now add a button which wraps an image (you bar item’s symbol!) You can also determine what should happen when the user taps on the bar item.


struct ContentView: View {

    @State var items = [Item]()

    var body: some View {
        //1. Embed your View into a Navigation View
        NavigationView {
            List(items) { item in
                Text(item.name)
            }
            //2. Add a Title for your Navigation Bar
            .navigationBarTitle(Text("To-Do"), displayMode: .inline)
            //.3 Add the Bar Items
            .navigationBarItems(trailing:
                HStack {
                    Button(action: {self.addTask()}) {
                    Image(systemName: "plus.circle")
                    }
                Button(action: {self.addTask()}) {
                    Image(systemName: "minus.circle")
                    }
                })
        }
    }

    func addTask() {
        let item = Item(id: items.count+1, name: "Sample Task")
        items.append(item)
    }

    func removeTask() {
        items.removeLast()
    }
}

struct Item: Identifiable {
    var id: Int
    var name: String
}

And that’s it! Now you’re able to create your own Navigation Bar with custom items in SwiftUI.


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

1 reply on “SwiftUI – How to create a Navigation Bar with custom items”

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount

small_c_popup.png

Are you ready for a new era of iOS development?

Start learning swiftUI today - download our free e-book