问题
Let me show the simple source code:
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")
}
}
}
}
Before navigate to MyDetailView, I want to do something, for example: save some data, or change some variable...
How could I do that?
It may be a simple question, but I really don't know.
Thanks for your help!
回答1:
I have got a simple method to resolve that:
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")
}
}
}
}
回答2:
You can handle methods from lifecycle using:
.onAppear {
print("ContentView appeared!")
}
And:
.onDisappear {
print("ContentView disappeared!")
}
check this tutorial: https://www.hackingwithswift.com/quick-start/swiftui/how-to-respond-to-view-lifecycle-events-onappear-and-ondisappear
So, you can use the .onDisappear
to perform any action you need
来源:https://stackoverflow.com/questions/58572063/how-could-i-do-something-before-navigate-to-other-view-by-navigationlink