Search code examples
iosswiftuser-interfaceswiftuinavigationview

Creating a custom back button with NavigationView on SwiftUI


I'm trying to create a custom back button on SwiftUI, but I can't figure out how to do it.

The idea is to hide the "Back" button at the top left that provides NavigationView, and make a custom button with the same functionality.

struct AnadirDatosViewA: View {
    @Environment(\.presentationMode) var presentation
    
    var body: some View{
        NavigationView(){
            Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)
                .edgesIgnoringSafeArea(.all)
                .overlay(
                    VStack{
                        AnadirDatosExpB()
                        
                        HStack{
                            
                            NavigationLink(destination:NuevoExperimentoView()){
                                Text("Back") //HERE
                                
                                NavigationLink(destination:AnadirDatosExpA()){
                                    Text("Next")
                                        
                                }
                            }
                        }
                    }
                )
        }.navigationBarBackButtonHidden(true)
    }
}

Right now I'm "cheating" by using the view I want go go back as destination, but it doesn't work the same...

What can I do?


Solution

  • It seems like presentationMode is going to be deprecated in the future, so instead you could also do

        @Environment(\.dismiss) var dismiss
    

    paired with

    Button(action: {
                    dismiss()
                }, label: {
                    Image(systemName: "chevron.left")
                    Text(bookClub.bookTitle)
                        .fontWeight(.bold)
                })