简体   繁体   中英

SwiftUI: horizontal ScrollView inside NavigationLink breaks navigation

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?

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) {}
            )
        }
    }
}

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.")
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM