Swiftui 在通过NavigationLink导航到其他视图之前,我如何执行某些操作?

Swiftui 在通过NavigationLink导航到其他视图之前,我如何执行某些操作?,swiftui,navigationlink,Swiftui,Navigationlink,让我展示一下简单的源代码: struct ContentView : View { @State var isPresented = false var body: some View { NavigationView { HStack{ NavigationLink(destination: MyDetailView(message: "Detail Page #2

让我展示一下简单的源代码:

struct ContentView : View {

    @State var isPresented = false
    var body: some View {        
            NavigationView {
                HStack{
                    NavigationLink(destination: MyDetailView(message: "Detail Page #2") ) {
                        Text("Go detail Page #2 >")
                    }
                    .navigationBarTitle("Index Page #1")
                }
            }

    }
}
在导航到MyDetailView之前,我想做一些事情,例如:保存一些数据,或者更改一些变量

我怎么能这么做

这可能是一个简单的问题,但我真的不知道


谢谢你的帮助

您可以使用以下方法处理生命周期中的方法:

   .onAppear {
        print("ContentView appeared!")
    }
以及:

检查本教程:


因此,您可以使用
.onDisappear
执行任何需要的操作

我有一个简单的方法来解决这个问题:

struct ContentView : View {

    @State var isPresented = false
    var body: some View {        
            NavigationView {
                HStack{
                    NavigationLink(destination: MyDetailView(message: "Detail Page #2") ,isActive: $isPresented) {
                        Text("Go detail Page #2 >")
                            .onTapGesture
                             {
                                 //Do somethings here
                                 print("onTapGesture")
                                 //Navigate
                                 self.isPresented = true
                             }
                    }
                    .navigationBarTitle("Index Page #1")
                }
            }

    }
}

另一个问题:如果我有两个NavigationList,例如:cancel和save,我怎么知道我单击了哪个NavigationList?你是说NavigationLink?您可以使用
@State var
处理此问题。如果单击“保存”,则将其修改为“保存”,与“取消”相同。如果这是你想要的。。对不起,我没有收到你的问题。这是正确的答案,是实现目标的简单有效的方法。
struct ContentView : View {

    @State var isPresented = false
    var body: some View {        
            NavigationView {
                HStack{
                    NavigationLink(destination: MyDetailView(message: "Detail Page #2") ,isActive: $isPresented) {
                        Text("Go detail Page #2 >")
                            .onTapGesture
                             {
                                 //Do somethings here
                                 print("onTapGesture")
                                 //Navigate
                                 self.isPresented = true
                             }
                    }
                    .navigationBarTitle("Index Page #1")
                }
            }

    }
}