Hi! I am trying to implement a button that shows an popup message and then immediately navigate to next view. However, the navigation push does not happen after the alert is displayed. Can you help me to find a solution?
Below is how the code I have looks like:
struct ContentView: View {
@State var showDetail: Bool = false
@State private var displayPopupMessage: Bool = false
var body: some View {
VStack {
NavigationLink(destination: DetailView(), isActive: self.$showDetail) {EmptyView()}
Button(action: {showDetail = prepossess()}) {Text(“Alert and Navigate”)}
}
.alert(isPresented: self.$displayPopupMessage){
Alert(title: Text(“Warning”), message: Text(“This is a test”), dismissButton: .default(Text("OK")))}
}
private func prepossess() -> Bool {
self.$displayPopupMessage = true
return true
}
}
When I pressed the button, the alert message will show up, but the navigation will not happen, neither before or after dissmissing the alert message. I debugged into the "action" closure of the button, and found the value of the "showDetail" state variable was updated.
I attempted to use the legacy UIAlert from UIKit instead of the new SwiftUI machenism, but still got the same result.
Can you give me some idea how to have the navigation follow the alert?
For some reason (may be the playground environment), preprocess() does not work.
But I modified the code and made it work with this:
I put
self.showDetail = true
into the "OK" action
struct ContentView: View {
@State var showDetail: Bool = false
@State private var displayPopupMessage: Bool = false
var body: some View {
VStack {
NavigationLink(destination: DetailView(), isActive: self.$showDetail) { EmptyView() }
Button(action: {
self.displayPopupMessage = true
// self.showDetail = true
// self.displayPopupMessage = self.prepossess()
} )
{
Text("Alert and Navigate")
}
}
.alert(isPresented: $displayPopupMessage){
Alert(title: Text("Warning"), message: Text("This is a test"), dismissButton: .default(Text("OK"), action: {
print("Ok Click")
self.showDetail = true
})
)
}
}
// private func prepossess() -> Bool {
// self.displayPopupMessage = true
// return true
// }
}