本文介绍了除了导航到另一个视图之外,NavigationLink 是否可以执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个按钮,它不仅可以导航到另一个视图,还可以同时运行一个函数.我尝试将 NavigationLink 和 Button 嵌入到 Stack 中,但我只能点击 Button.

I'm trying to create a button that not only navigates to another view, but also run a function at the same time. I tried embedding both a NavigationLink and a Button into a Stack, but I'm only able to click on the Button.

ZStack {
    NavigationLink(destination: TradeView(trade: trade)) {
        TradeButton()
    }
    Button(action: {
        print("Hello world!") //this is the only thing that runs
    }) {
        TradeButton()
    }
}

推荐答案

您可以使用 .simultaneousGesture 来做到这一点.NavigationLink 将在导航的同时执行您想要的操作:

You can use .simultaneousGesture to do that. The NavigationLink will navigate and at the same time perform an action exactly like you want:

NavigationLink(destination: TradeView(trade: trade)) {
                        Text("Trade View Link")
                    }.simultaneousGesture(TapGesture().onEnded{
                    print("Hello world!")
                })

这篇关于除了导航到另一个视图之外,NavigationLink 是否可以执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 07:10