Search code examples
swiftuinavigationnavigationbar

Add Back Button to UINavigationBar SwiftUI


I had to customize my navigation bar for reasons outlined in this post, but SwiftUI is now not generating back buttons for me automatically. How can I add them?

See my sample code:

struct ContentView: View {

init() {
    
    let coloredAppearance = UINavigationBarAppearance()
    coloredAppearance.configureWithOpaqueBackground()
    coloredAppearance.backgroundColor = .white
    coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.black]
    coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.black]
    
    UINavigationBar.appearance().standardAppearance = coloredAppearance
    UINavigationBar.appearance().compactAppearance = coloredAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    
    UINavigationBar.appearance().tintColor = .white
}
    var body: some View {
        NavigationView {
            NavigationLink(destination: NavigationLink(destination: Color.purple) {
                Text("Continue")
                    .navigationTitle("Nav Title 2")
                    .navigationBarTitleDisplayMode(.inline)
            }) {
                Text("Continue")
                    .navigationTitle("Nav Title 1")
                    .navigationBarTitleDisplayMode(.inline)
            }
        }
    }
}

Solution

  • In your sample code, back buttons are generated but in white color, as a consequence they are not visible in the navigation bar.

    To display back buttons change:

    UINavigationBar.appearance().tintColor = .white
    

    To:

    UINavigationBar.appearance().tintColor = UIColor(.accentColor)