我想给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")}
        }发布于 2021-11-24 16:09:53
适用于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()
        }
}我找不到原始代码,但这个解决方案非常适合我。
https://stackoverflow.com/questions/60549028
复制相似问题