Change the color of back button on NavigationView

In this tutorial, we’ll learn how to change the color of the back button on NavigationView in SwiftUI. It’s super easy all we have to do is use one SwiftUI modifier, the accentColor modifier. By using these modifiers we can change the color of the back button of navigationView.

Let’s see how we change the back button color in SwiftUI:

struct ContentView: View {
    var body: some View {
     
            VStack(spacing: 20) {
                Text("Hello, world!")
              
                NavigationLink(destination: Text("New Text")) {
                    Text("Tap to navigate").foregroundColor(Color.teal)
                }
                
            }
            .padding()
            
    }
}

Currently, ContentView, which is the main view, looks like this. Let’s just grab the code in a NavigationView.

 

struct ContentView: View {
    var body: some View {
     
        NavigationView{
          
            VStack(spacing: 20) {
                Text("Hello, world!")
              
                NavigationLink(destination: Text("New Text")) {
                    Text("Tap to navigate").foregroundColor(Color.teal)
                }
                
            }
            .padding()
            
        }
    }
}

 

Now, let’s create a new view to which we’ll navigate. Press cmd+N and give it a name, “newView” or any other name you would like to have.

 

struct newView: View {
    var body: some View {
        VStack{
         
            Text("Hello, World! from newView").bold()
            
            
        }

    }
    
}

Now in the mainView, ContentView, Give the NavigationView a color by using the accentColor modifier. The back button on the next screen will have the same color which we’ll give to NavigationView.

 

struct ContentView: View {
    var body: some View {
     
        NavigationView{
          
            VStack(spacing: 20) {
                Text("Hello, world!")
              
                NavigationLink(destination: Text("New Text")) {
                    Text("Tap to navigate").foregroundColor(Color.teal)
                }
                
            }
            .padding()
            
        }.accentColor(.teal)
    }
}

 

We can also use the .tint() modifier of SwifUI for achieving the same results.

Wait for few seconds to see the output. As it’s gif image.

 

Change the color of back button on NavigationView

Leave a Reply

Your email address will not be published. Required fields are marked *