5

I have a SwiftUI View that pushes a new detail view using a regular NavigationLink:

NavigationLink(destination: DetailView() ) { Text("Show Detail View") } 

I need a workaround to prevent the detail view from popping when the user presses the back button. I couldn't find a SwiftUI native way to do that.

4
  • 1
    That will be confusing for user, don't you want just hide back button with navigationBarBackButtonHidden? And that's it: no back button - no back navigation. Commented Mar 8, 2020 at 11:04
  • I need to display a message to the user in a specific case and prevent the pop, and in other cases i need the popping to work as is. Commented Mar 8, 2020 at 11:05
  • 1
    What about custom back button as leading navigation bar item? You'd have full control over action in there. Commented Mar 8, 2020 at 11:06
  • would you post this as an answer Commented Mar 8, 2020 at 11:09

1 Answer 1

4

Please find below a possible approach using custom back button (note: adding any leading navigation bar item disables default back button automatically)

Tested with Xcode 11.2 / iOS 13.2

struct DemoDetailsWithCustomBack: View { @Environment(\.presentationMode) var presentationMode @State private var allowsBack = true var body: some View { Text("Details here") .navigationBarItems( leading: Button(action: { if self.allowsBack { self.presentationMode.wrappedValue.dismiss() } else { // activate alert here } }, label: { Image(systemName: "chevron.left") }) ) } } struct TestNavBarButton_Previews: PreviewProvider { static var previews: some View { NavigationView { NavigationLink(destination: DemoDetailsWithCustomBack() ) { Text("Show Detail View") } } } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.