Swift and SwiftUI tutorials for Swift Developers

How to build a Custom Back Button in SwiftUI

In this article we will see how we can create our own custom Back button. Here is how we can implement it:

-Hide the original Back button.
-Create a custom Back button and assign it as the left button of the navigation bar.

To hide the default Back button, SwiftUI provides the navigationBarBackButton Hidden modifier. Setting its value to true will hide the original Back button:

.navigationBarBackButton(true)

Once the Back button has been hidden, you can replace it with your own button. The toolbar modifier allows us to configure the items of the navigation bar. We create the custom Back button using ToolBarItem and assigning the button to the left side of the navigation bar. Here is the code in Swift:

.toolbar{
            
            ToolbarItem(placement: .navigationBarLeading){
                
                Button(action: {
                    
                    //Navigate to the previous screen
                    
                }) {
                    
                    Image(systemName: "chevron.left.circle.fill")
                        .font(.largeTitle)
                }
                .tint(.white)       
            }
            
            
        }

In XCode it gives the following result:

You may have noticed that the button action has been left blank. The button has been drawn perfectly on the canvas but the problem is that it doesn’t work.

The original button rendered by NavigationStack can automatically navigate to the previous screen. We need to programmatically navigate back. Thanks to the environment variables we have in the SwiftUI framework. We can use the dismiss environment binding to close the current view.

All that remains is to declare a dismiss variable as follows to capture the environment variable:

@Environment(.dismiss) var dismiss

In the action of our custom back button, we insert this line of code:

dismiss()

We call the dismiss() method to dismiss the detail view when the back button is pressed.

Leave a Reply

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

Previous Article

What is .ignoresSafeArea() in SwiftUI

Next Article

How to use Sheet in SwiftUI

Related Posts