4

I want to use a simple horizontal ScrollView as NavigationLink inside a List. However, tapping on the ScrollView is not registered by a NavigationLink and therefore does not navigate to the destination.

NavigationView {
    List {
        NavigationLink(destination: Text("Detail")) {
            ScrollView(.horizontal) {
                Text("Tapping here does not navigate.")
            }
        }
    }
}

Any ideas on how can we prevent ScrollView from capturing the navigation tap gesture?

damirstuhec
  • 6,069
  • 1
  • 22
  • 39

2 Answers2

3

You can move NavigationLink to the background and activate it in onTapGesture:

struct ContentView: View {
    @State var isLinkActive = false
    
    var body: some View {
        NavigationView {
            List {
                ScrollView(.horizontal) {
                    Text("Tapping here does not navigate.")
                }
                .onTapGesture {
                    isLinkActive = true
                }
            }
            .background(
                NavigationLink(destination: Text("Detail"), isActive: $isLinkActive) {}
            )
        }
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • This works, but it's a hack/workaround I'm already aware of and was trying to avoid with a potential native approach. Thanks! – damirstuhec Oct 27 '20 at 10:10
  • @damirstuhec What you've tried in your question looks like it should (probably) be the *native* way. But it's not (at least in SwiftUI 2). So you might still need to use workarounds/hacks (as you often do with SwiftUI). – pawello2222 Oct 27 '20 at 17:25
  • Agree. It feels like a bug, so let's hope that's fixed soon. I filed feedback. – damirstuhec Oct 27 '20 at 18:48
2

The final goal is not clear, but the following alternate does also work (tested with Xcode 12 / iOS 14)

NavigationView {
    List {
        ScrollView(.horizontal) {
            NavigationLink(destination: Text("Detail")) {
                Text("Tapping here does not navigate.")
            }
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    This works, however, I simplified my question example a bit too much. In reality, I want a navigation link row, which contains other views besides the scroll view. Moving the ScrollView outside of the NavigationLink, as you're suggesting, would make the whole row contents scroll, which is not what I want. – damirstuhec Oct 27 '20 at 10:09