Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom navbar back button in SwiftUI

Tags:

ios

swift

swiftui

I have been trying to look up how to add custom navbar back button in SwiftUI but I get this strange behaviour, that the default behaviour still appears before the custom one is shown. does anyone know the proper way to add it?

Here is what I tried.

var body: some View {
        NavigationView {
            ZStack {
               Color.background.edgesIgnoringSafeArea(.all)
               NavigationLink(destination: UserDetailsView()) {
                        Text("Continue")
                            .foregroundColor(.background)
                            .font(.title)
                            .fontWeight(.semibold)
                    }
                    .frame(width: 250, height: 60, alignment: .center)
                    .background(Color.white)
                    .cornerRadius(40)
                    .padding(.top, 50)
            }
            .navigationBarTitle("", displayMode: .automatic)
            .navigationBarHidden(true)
        }
      }

Here when I use the below code to hide back button it doesn't even hide at all.

.navigationBarBackButtonHidden(true)

In details screen

  var body: some View {
        NavigationView {
            VStack {
                ZStack {
                    Rectangle()
                        .foregroundColor(.clear)
                        .background(gradient)
                        .edgesIgnoringSafeArea(.all)

                    Text("Hello")
                }
            }
            .navigationBarItems(leading: BackButton(presentationMode: presentationMode))
        }
    }

The custom back button looks like this

struct BackButton: View {
    var presentationMode : Binding<PresentationMode>

    var body: some View {
        Button(action: {
            self.presentationMode.wrappedValue.dismiss()
        }) {
            HStack {
                Image(Icon.leftArrow)
                    .aspectRatio(contentMode: .fit)
                    .foregroundColor(.black)
            }
        }
    }
}

Here is the what it looks like enter image description here

like image 558
bona912 Avatar asked Dec 15 '25 04:12

bona912


1 Answers

Thanks for the hints. It works for me.... BUT after adding a

.navigationBarItems(leading:  ... 

the swipe-to-go-back no longer works. I'm guessing this is a bug in SwiftUI ?

Have anybody found a workaround for this?

like image 63
Bo Frese Avatar answered Dec 16 '25 19:12

Bo Frese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!