swiftformsswiftuinavigationlink

SwiftUI: NavigationLink unintentionally tappable and activated inside Form


I seem to have a problem where a NavigationLink is being reformatted in a Form. My NavigationLink is activated via isActive upon a button press that toggles showNext.

The problem is that the NavigationLink seems to be activated on its own even when the button doesn't exist by tapping the empty row which the Form seems to create for the NavigationLink which should just be an EmptyView. It seems like the Form creates rows even for EmptyViews.

So I was thinking there might be some possible solutions, but I'm not sure if these are possible:

(1) Somehow hide the row created for the NavigationLink/EmptyView completely without disabling the navigating behavior.

(2) Override the Form formatting of NavigationLink so that it's not activated upon tap.

EDIT: Seems like option 2 is possible with .disabled(true) but the empty section is still visible which is undesirable on top of this seeming a bit hacky.

struct FormView  : View {
    @State var showNext: Bool = false

    var body: some View {
        NavigationView {
            Form {
               Section {
                   VStack {
                       Text("Hello")

                       NavigationLink(destination: Text("Detail View"), isActive: $showNext) 
                       { EmptyView() }
                   }
               }
            }
        }
    }
}

Solution

  • The solution is to hide link into background of some view, like below

    Form {
     Section {
       VStack {
          Text("Hello")
            .background(
               NavigationLink(destination: Text("Detail View"), isActive: $showNext)
                 { EmptyView() }.disabled(!showNext)
             )
         }
       }
    }