在一个SwiftUI视图中,我通过创建一个包含一些文本的NavigationView的VStack实现了一个垂直滚动列表。我通过遍历popularFeedTypes对象来构建它,为popularFeedTypes对象中的每一项创建一个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)
}
}
我遇到的问题是,如果我在NavigationLink上有一个onTapGesture操作,我会在模拟器中体验到不同的行为,这取决于我单击该行的方式。如果我单击行右侧的文本或箭头(>),onTapGesture将会触发,但不会出现导航。如果我单击文本和箭头之间的空白处,onTapGesture不会触发,但会进行导航。如果我删除onTapGesture代码,单击这三个位置中的任何一个都会导致导航发生。所以我的问题是,即使存在onTapGesture操作,导航也不应该发生吗?同样,无论您在构成NavigationLink的行上单击什么位置,onTapGesture操作都不应该触发吗?
发布于 2020-08-31 22:29:27
你可以使用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)
}
}
发布于 2020-05-27 04:58:00
如果您想同时执行操作和导航,您可以这样做:
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)
}
}
发布于 2020-08-20 10:37:37
如果要在触发导航链接之前执行某些操作,可以使用tag
和selection
初始化导航链接。
struct someViewName: View {
@State var navigationLinkTriggerer: Bool? = nil
@State var navigationLinkFeedType: FeedType
var body: some View {
VStack {
NavigationLink(destination: FeedTypeView(feedType: navigationLinkFeedType),
tag: true,
selection: $navigationLinkTriggerer) {
EmptyView()
}
NavigationView {
List (self.popularFeedTypes.popularFeedTypes!, id: \.self) { feedType in
Button(feedType) {
// do all you want here
print("TAPPED")
// then set the navigationLinkTriggerer to value of you navigation link `tag`
// in this case tag is equal to `true`
// this will trigger the navigation link
self.navigationLinkFeedType = feedType
self.navigationLinkTriggerer = true
}
}
.navigationBarTitle(Text("Discover"), displayMode: .inline)
}
}
}
}
https://stackoverflow.com/questions/59040566
复制相似问题