Instead of using UIKit APIs to customize the Back button, an alternative approach is to hide the default Back button and create our own Back button in SwiftUI. To hide the Back button, you can use the .navigationBarBackButtonHidden modifier and set its value to true. Here is an example of how you can do this in the detail view:
.navigationBarBackButtonHidden(true)
SwiftUI also offers a modifier called toolbar to create your own navigation bar elements.
Here is an example of how we can use it:
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button{
dismiss()
} label: {
Text("\(Image(systemName: "chevron.left")) Custom Back Button")
.foregroundColor(.black)
}
}
}
In the .toolbar modifier’s closure, we create a ToolbarItem object with the location set to .navigationBarLeading. This specifies that the button should be located at the leading edge of the navigation bar.
In order to put this code into action, we need to declare the .dismiss key as follows:
@Environment(.dismiss) var dismiss
The result in XCode is as follows:
SwiftUI offers a wide range of built-in environment values. To dismiss the current view and return to the previous view, we can retrieve the environment value using the .dismiss key. We can then call the dismiss() function to dismiss the current view. Note that the .dismiss environment key is only available on iOS 15 or later. If you need support for an older version of iOS, you can use the .presentationMode environment key:
@Environment(\.presentationMode) var presentationMode
Then you can call the presentation mode’s dismiss function like this:
presentationMode.wrappedValue.dismiss()