NavigationLink onTapGesture 和导航未一致触发

Chr*_*ger 9 swiftui

在 SwiftUI 视图中,我通过创建一个包含 NavigationView(其中包含一些文本)的 VStack 来实现垂直滚动列表。我通过循环遍历流行的FeedTypes对象来构建它,为流行的FeedTypes对象中的每个项目创建一个NavigationLink。如果用户单击 NavigationLink,则会将用户推送到名为 FeedTypeView 的新视图。您可以看到下面的代码。

VStack{
    NavigationView{
        List (self.popularFeedTypes.popularFeedTypes!, id: \.self) { feedType in
            NavigationLink(destination: FeedTypeView(feedType: feedType)) {
                Text(feedType.feedType)
            }.onTapGesture {
                print("TAPPED")
            }
        }
        .navigationBarTitle(Text("Discover"), displayMode: .inline)
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,如果我在 NavigationLink 上有 onTapGesture 操作,我会在模拟器中体验到不同的行为,具体取决于我单击该行的方式。如果我单击行右侧的文本或箭头 (>),则会触发 onTapGesture,但不会发生导航。如果我单击文本和箭头之间的空间,onTapGesture 不会触发,但会发生导航。如果我删除 onTapGesture 代码,单击这三个位置中的任何一个都会导致导航发生。所以我的问题是,即使存在 onTapGesture 操作,导航也不应该发生吗?另外,无论您单击构成 NavigationLink 的行的何处,onTapGesture 操作是否都不应触发?

Tar*_*riq 5

VStack {
    NavigationView{
        List (self.popularFeedTypes.popularFeedTypes!, id: \.self) { feedType in
            NavigationLink(destination: FeedTypeView(feedType: feedType)) {
                Text(feedType.feedType)
            }
            .simultaneousGesture(TapGesture().onEnded {
                print("TAPPED")
            })
            .buttonStyle(PlainButtonStyle())
        }
        .navigationBarTitle(Text("Discover"), displayMode: .inline)
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该有效。使用simultaneousGestureNavigationLink

  • @MatheusCâmara - 这段代码对我有用。 (3认同)

Vic*_*rov 5

您可以使用 onAppear 来处理点击事件。

VStack {
    NavigationView {
        List(self.popularFeedTypes.popularFeedTypes!, id: \.self) { feedType in
            NavigationLink(
                destination: FeedTypeView(feedType: feedType).onAppear { print("TAPPED") }) {
                Text(feedType.feedType)
            }
        }
        .navigationBarTitle(Text("Discover"), displayMode: .inline)
    }
}
Run Code Online (Sandbox Code Playgroud)


Ant*_*ton 2

如果您想同时执行操作和导航,您可以这样做:

VStack{
        NavigationView{
            List (self.popularFeedTypes.popularFeedTypes!, id: \.self) { feedType in
                NavigationLink(destination: FeedTypeView(feedType: feedType)) {
                    Text(feedType.feedType)
                }
                .simultaneousGesture(TapGesture().onEnded{
                    print("TAPPED")
                })
            }
            .navigationBarTitle(Text("Discover"), displayMode: .inline)
        }
    }
Run Code Online (Sandbox Code Playgroud)