Home > Blockchain >  NavigationBar with Custom Back Text but no NavigationBarTitle
NavigationBar with Custom Back Text but no NavigationBarTitle

Time:08-03

I want to hide the navigationbarTitle for my views, but keep a custom value for the back button in the child views. So the NavigationBar should be visible in every screen, but should not have a title. But i want to change the text 'Back' to a custom text.

NavigationLink {
    SomeChildView()
} label: {
    SomeView()
}.navigationBarTitle("Text for back button in child view")

If I set the title on the NavigationLink this gives me my custom back button text but also displays the title in the Parent View.

CodePudding user response:

You can achieve what you need by using the environment value of presentationMode to dismiss the screen you are in by code, and for changing the back button label and style you can simply do

  1. hide the back button by using .navigationBarBackButtonHidden(true) modifier
  2. use toolbar and toolbarItem to add your custom back button to the NavigationBar

here an example of how you can use it

// FirstScreen
struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink {
                SecondScreen()
            } label: {
                Text("Go To Second Screen")
            }
        }
    }
}
// SecondScreen
struct SecondScreen: View {
    @Environment(\.presentationMode) var presentationMode
    var body: some View {
        Text("Second Screen")
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button {
                        presentationMode.wrappedValue.dismiss()
                    } label: {
                        Label("Custom Back Button", systemImage: "command")
                            .labelStyle(.titleAndIcon)
                    }

                }
            }
    }
}
  • Related