Is it possible to disable the back navigation menu in SwiftUI?

57 Views Asked by At

When we long tap on the back button it shows menu. I know it can be hidden in UIKit using navigation item, but is there any way for SwiftUI?

1

There are 1 best solutions below

0
Mahi Al Jawad On

Xcode 15.2 and iOS 17.2

I have made a demo application to show the operation. Update with your own logic and customization to update Back button enable/disable logic.

import SwiftUI


struct ContentView: View {
    var body: some View {
        NavigationStack {
            NavigationLink("Go To Detail",
                           destination: BackButtonView())
            .font(.title)
            .navigationTitle("Navigation Views")
        }
    }
}

// Second Screen
struct BackButtonView: View {
    // Enable or disable this State var whenever you need
    @State var isBackButtonEnabled = true
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        Toggle("Enable back button", isOn: $isBackButtonEnabled) // Update your back button enable/disable logic as you wish
            .padding()
            .navigationTitle("Back button View")
            .navigationBarBackButtonHidden(true) // Disables default navigation back button
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button(action:  {
                        // Add your code to navigate back
                        // If you use NavigationPath based navigation then update your path
                        dismiss()
                    }, label: {
                        Text("Back")
                    })
                    .disabled(!isBackButtonEnabled) // Here's the main game
                }
            }
    }
}

Output simulation:

Back button disable demo