我的列表单元格中有两个NavigationLink
我想在单击一次时转到目标1,然后在单击两次时转到目标2。 因此,我添加了两个轻击手势来控制导航。
但是当我点击时,有两个问题:
这是我的代码:
struct MultiNavLink: View {
@State var mb_isActive1 = false;
@State var mb_isActive2 = false;
var body: some View {
return
NavigationView {
List {
ZStack {
NavigationLink("", destination: Text("Destination1"), isActive: $mb_isActive1)
NavigationLink("", destination: Text("Destination2"), isActive: $mb_isActive2)
Text("Single tap::go to destination1\nDouble tap,go to destination2")
}
.onTapGesture(count: 2, perform: {()->Void in
NSLog("Double tap::to destination2")
self.mb_isActive2 = true
}).onTapGesture(count: 1, perform: {()->Void in
NSLog("Single tap::to destination1")
self.mb_isActive1 = true
})
}.navigationBarTitle("MultiNavLink",displayMode: .inline)
}
}
}
我尝试删除List元素,然后一切按预期进行。 似乎是List元素使一切变得奇怪。
我发现了这个问题:SwiftUI - Two buttons in a List,但情况与我不同。
期待您的回答,非常感谢...
答案 0 :(得分:1)
尝试以下方法-想法是将链接隐藏在可见内容的背景中,并使它们对于UI无效,但通过编程方式激活。
通过Xcode 12 / iOS 14测试。
struct MultiNavLink: View {
var body: some View {
return
NavigationView {
List {
OneRowView()
}.navigationBarTitle("MultiNavLink", displayMode: .inline)
}
}
}
struct OneRowView: View {
@State var mb_isActive1 = false
@State var mb_isActive2 = false
var body: some View {
ZStack {
Text("Single tap::go to destination1\nDouble tap,go to destination2")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.contentShape(Rectangle())
.background(Group {
NavigationLink(destination: Text("Destination1"), isActive: $mb_isActive1) {
EmptyView() }
.buttonStyle(PlainButtonStyle())
NavigationLink(destination: Text("Destination2"), isActive: $mb_isActive2) {
EmptyView() }
.buttonStyle(PlainButtonStyle())
}.disabled(true))
.highPriorityGesture(TapGesture(count: 2).onEnded {
self.mb_isActive2 = true
})
.onTapGesture(count: 1) {
self.mb_isActive1 = true
}
}
}
答案 1 :(得分:0)
导航链接具有一个初始化器,该初始化器采用绑定selection
,并且只要将selection
设置为NavigationLink tag
的值,就会触发导航链接。
提示:如果应用无法区分和识别您的点击,即使有两次点击,仍然会触发一次点击的动作,那么您可以使用同时手势(.simultaneousGesture()
)修饰符代替普通手势(.gesture()
)修饰符。
struct someViewName: View {
@State var navigationLinkTriggererForTheFirstOne: Bool? = nil
@State var navigationLinkTriggererForTheSecondOne: Bool? = nil
var body: some View {
VStack {
NavigationLink(destination: SomeDestinationView(),
tag: true,
selection: $navigationLinkTriggererForTheFirstOne) {
EmptyView()
}
NavigationLink(destination: AnotherDestinationView(),
tag: true,
selection: $navigationLinkTriggererForTheSecondOne) {
EmptyView()
}
NavigationView {
Button("tap once to trigger the first navigation link.\ntap twice to trigger the second navigation link.") {
// tap once
self.navigationLinkTriggererForTheFirstOne = true
}
.simultaneousGesture(
TapGesture(count: 2)
.onEnded { _ in
self.navigationLinkTriggererForTheSecondOne = true
}
)
}
}
}
}