Remove the text from back button in SwiftUI

CodeBender picture CodeBender · Aug 6, 2019 · Viewed 7.2k times · Source

In short, I want to do this, but with SwiftUI.

enter image description here

(Home should be removed)

So far, I have not found a way to access the NavigationBarButton directly, and have managed to find the following that appears to be the only way I can find to date for modifying the button:

struct MyList: View {
    var body: some View {
            Text("MyList")
            .navigationBarTitle(Text(verbatim: "MyList"), displayMode: .inline)
            .navigationBarItems(leading: Text("<"))
    }
}

However, I lose the default return image and get an ugly < instead.

enter image description here

Answer

kontiki picture kontiki · Aug 6, 2019

You need to set the title of the view that the back button will pop to:

struct ContentView: View {    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailView()) {
                    Text("push view")
                }
            }.navigationBarTitle("", displayMode: .inline)
        }
    }
}

struct DetailView: View {    
    var body: some View {
        Text("Detail View")
    }
}

Alternatively, to conditionally set or unset the title of the source view, depending on the presentation status you can use the code below.

Beware that the isActive parameter has a bug, but that will most likely be solved soon. Here's a reference to the bug mentioned SwiftUI: NavigationDestinationLink deprecated

struct ContentView: View {
    @State private var active: Bool = false

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailView(), isActive: $active) {
                    Text("push view")
                }
            }.navigationBarTitle(!active ? "View Title" : "", displayMode: .inline)
        }
    }
}

struct DetailView: View {
    var body: some View {
        Text("Detail View")
    }
}