本文介绍了SwiftUI NavigationLink:如何在显示目标视图之前调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想调用一个函数,之后点击一个项目,之前显示目标视图.
I would like to call a function, after clicking on an item, and before displaying the destination view.
以下代码似乎不起作用:调用了 myFunction
,但未显示目标视图.
The code below doesn't seem to work: myFunction
is called, but the destination view is not shown.
看起来 onTapGesture
覆盖了 NavigationLink
目标.
It looks like the onTapGesture
overwrites the NavigationLink
destination.
NavigationView {
List(restaurants) { restaurant in
NavigationLink(destination: RestaurantView(restaurant: restaurant)) {
RestaurantRow(restaurant: restaurant)
}.onTapGesture { myModel.myFunction(restaurant) }
}
}
如何在单击列表项时同时拥有两者?
How can I have both, when clicking on a list item?
- 函数被调用
- 显示目的地视图
推荐答案
尝试将 NavigationLink
添加到 Button
中,例如:
Try to add NavigationLink
into a Button
, like:
Button(action: {
//Call here
myModel.myFunction(restaurant)
}, label: {
NavigationLink(destination: RestaurantView(restaurant: restaurant)) {
RestaurantRow(restaurant: restaurant)
}
})
EDIT粘贴测试代码,直接试试
EDIT pasted test code, try directly
struct TestNavigationView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Detail").onAppear() {
test()
}) {
Text("Click")
}
}
}
}
func test() {
print("Hell0")
}
}
另一种方法:(如果 List
在那里可能不起作用)
another approach: (might not work if List
there)
struct TestNavigationView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Detail")) {
Text("Click")
}.simultaneousGesture(TapGesture().onEnded{
test()
})
}
}
}
func test() {
print("Hell0")
}
}
这篇关于SwiftUI NavigationLink:如何在显示目标视图之前调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!