Custom Navigation in SwiftUI

Finished Product

Standard Navigation Controllers given within swiftUI’s framework are great and allow for quite a bit of flexibility. Sometimes though, they are missing a key piece of functionality you are looking for, or maybe you don’t like the standard transition included in them.

Luckily, implementing your own custom solution to navigation is easy, and does not require much more work compared to a standard navigation controller once set up.

First:

Set up a custom struct which will be your actual navigation bar

This Struct has fields for the button shown before the title, the title itself, and the buttons shown after the title. This allows for powerful flexibility when implementing in other views.

Next:

In the view you are planning on using the NavController, specify a State variable for the title, and two functions that will return the buttons you are planning on using for the nav controller.

Tip:

Wrapping your views with ‘AnyView’ when dealing with several different types of content in the same place. i.e Images, Buttons, Text, etc.

Lastly:

Implement the navigation controller in with your view in a VStack, passing in the variables you initialized!

Tip:

If you implement an if/else statement inside the group I specified above, you can use the same NavController for different views. Also, I have provided a sample transition to attach as a modifier on the group. When changing the bool that controls which view is shown with an animation, this transition replicates the look of the default transition style.

That is it! you can reuse the NavController at the top of any other view you would like.

Leave a Reply

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