有没有办法向 NavigationLink 添加额外的功能?斯威夫特用户界面

Is there a way to add an extra function to NavigationLink? SwiftUI

我想为 NavigationLink 添加一个额外的功能。

示例代码是这样的:

struct ContentView: View {

func yes () {
print("yes")
}

var body: some View {

NavigationView {
NavigationLink(destination: level1()) {

     Text("Next")      
}}}}

我知道这行不通,但是可以这样做吗? (会去目的地同时调用函数)

NavigationLink(destination: level1(), yes()) {Text("Next")}   

我尝试在 NavigationLink 中放置一个按钮,但它也不起作用。当我这样做时,只有按钮中的功能起作用,NavigationLink 不起作用。

NavigationLink(destination: level1())   {
        Button(action: { self.yes() }) 
        { Text("Button")}
        }

使用onAppear(perform:)。这将对 View 的出现执行某些功能。

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: DetailView().onAppear {
                self.someFunc()
            }) {
                Text("First Screen")
            }
        }
    }

    func someFunc() {
        print("Click")
    }
}

struct DetailView: View {
    var body: some View {
        Text("Second Screen")
    }
}

SwiftUI 解决方案,iOS 15.1 & Xcode 13.1.

import Foundation
import SwiftUI

// NavigationLink replacement with action
// Usage:
//var body: some View {
//  NavigationButton(
//      action: { print("tapped!") },
//      destination: { Text("Pushed View") },
//      label: { Text("Tap me") }
//  )
//}

struct NavigationButton<Destination: View, Label: View>: View {
        var action: () -> Void = { }
        var destination: () -> Destination
        var label: () -> Label

        @State private var isActive: Bool = false

        var body: some View {
                Button(action: {
                        self.action()
                        self.isActive.toggle()
                }) {
                        self.label()
                            .background(
                                ScrollView { // Fixes a bug where the navigation bar may become hidden on the pushed view
                                        NavigationLink(destination: LazyDestination { self.destination() },
                                                                                                 isActive: self.$isActive) { EmptyView() }
                                }
                            )
                }
        }
}

// This view lets us avoid instantiating our Destination before it has been pushed.
struct LazyDestination<Destination: View>: View {
        var destination: () -> Destination
        var body: some View {
                self.destination()
        }
}

我找不到原始代码,但这个解决方案非常适合我。