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?

2 Answers 2

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) {}
            )
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

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 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).
Agree. It feels like a bug, so let's hope that's fixed soon. I filed feedback.
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.")
            }
        }
    }
}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.