I want to add a custom navigation button that will look somewhat like this:
Now, I've written a custom BackButton
view for this. When applying that view as leading navigation bar item, by doing:
.navigationBarItems(leading: BackButton())
...the navigation view looks like this:
I've played around with modifiers like:
.navigationBarItem(title: Text(""), titleDisplayMode: .automatic, hidesBackButton: true)
without any luck.
Question
How can I...
- set a view used as custom back button in the navigation bar? OR:
- programmatically pop the view back to its parent?
When going for this approach, I could hide the navigation bar altogether using.navigationBarHidden(true)
Based on other answers here, this is a simplified answer for Option 2 working for me in XCode 11.0:
Note: To get the NavigationBar to be hidden, I also needed to set and then hide the NavigationBar in ContentView.
TL;DR
Use this to transition to your view:
Add this to the view itself:
Then, in a button action or something, dismiss the view:
Full code
From a parent, navigate using
NavigationLink
In DetailsView hide
navigationBarBackButton
and set custom back button to leadingnavigationBatItem
,I expect you want to use custom back button in all navigable screens, so I wrote custom wrapper based on @Ashish answer.
Wrap screen content in NavigationItemContainer:
Usage:
I found this: https://ryanashcraft.me/swiftui-programmatic-navigation/
It does work, and it may lay the foundation for a state machine to control what is showing, but it is not a simple as it was before.
All of the solutions I see here seem to disable swipe to go back functionality to navigate to the previous page, so sharing a solution I found that maintains that functionality. You can make an extension of your root view and override your navigation style and call the function in the view initializer.
Sample View
Extension
The only downfall to this approach is I haven't found a way to remove/change the text associated with the custom back button.
Swift 1.0
It looks like you can now combine the
navigationBarBackButtonHidden
and.navigationBarItems
to get the effect you're trying to achieve.Code
Example
Here is what it looks like (excerpt from the "SwiftUI Views" book):