[英]SwiftUI onTapGesture block NavigationLink action
我想按List
的一个单元格来显示一个菜单,然后单击菜单通过NavigationLink
推送到一个新视图。
这是我的代码:
import SwiftUI
struct ContentView: View {
let array = ["a", "b"]
@State var isPushed: Bool = false
@State var isDisplayMenu: Bool = false
@State var isDestination1Clicked: Bool = false
var body: some View {
NavigationView {
List {
ForEach(array, id:\.self) { value in
VStack {
RowView(title: value)
.frame(maxWidth: .infinity)
if isDisplayMenu {
HStack {
ZStack {
Text("D1")
NavigationLink(
destination: Destination1(),
label: {
EmptyView()}).hidden()
}
ZStack {
Text("D2")
NavigationLink(
destination: Destination2(),
label: {
EmptyView()}).hidden()
}
}
}
}
.background(Color.green)
.contentShape(Rectangle())
.onTapGesture(count: 1, perform: {
isDisplayMenu.toggle()
})
}
}
}
}
}
struct Destination1: View {
var body: some View {
Text("D1")
}
}
struct Destination2: View {
var body: some View {
Text("D2")
}
}
struct RowView: View {
var title: String
var body: some View {
VStack {
Text("title")
Text(title)
}.background(Color.red)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
单击单元格时,将显示 D1 和 D2。 但是NavigationLink
不起作用。
我认为原因是onTapGesture
阻止了它。 我怎样才能使NavigationLink
工作?
有什么帮助吗? 谢谢!
List 中定义的一些限制只是一个 List 本身。
这样我们就不能在 List 单元格中使用多个 NavigationLink (如果我们使用多个,则无法获得预期的行为)
而且 Empty views 也不会获得触摸事件。
这是您的代码的修复程序。
struct ContentView: View {
let array = ["a", "b"]
@State var isPushed: Bool = false
@State var isDisplayMenu: Bool = true
@State var isDestination1Clicked: Bool = false
var body: some View {
NavigationView {
ScrollView {
ForEach(array, id:\.self) { value in
VStack {
RowView(title: value)
.frame(maxWidth: .infinity)
.background(Color.green)
.onTapGesture(count: 1, perform: {
withAnimation {
isDisplayMenu.toggle()
}
})
if isDisplayMenu {
HStack {
NavigationLink(
destination: Destination1(),
label: {
Spacer()
Text("D1")
.foregroundColor(.black)
Spacer()
})
NavigationLink(
destination: Destination2(),
label: {
Spacer()
Text("D2")
Spacer()
})
.foregroundColor(.black)
}
.background(Color.purple)
}
}
.padding()
.contentShape(Rectangle())
}
}
}
}
}
struct Destination1: View {
var body: some View {
Text("D1")
}
}
struct Destination2: View {
var body: some View {
Text("D2")
}
}
struct RowView: View {
var title: String
var body: some View {
VStack {
Text("title")
Text(title)
}.background(Color.red)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
尝试将“onTapGesture”附加到“NavigationView”。
NavigationView {
....
}.onTapGesture(count: 1, perform: {
isDisplayMenu.toggle()
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.