Search code examples
swiftswiftuiswiftui-navigationlinkswiftui-navigationview

How do I navigate to another screen by clicking on button in SwiftUI?


How do I make it so that it goes to ChatScreen when I click the "OK" button?

.alert(
    Text("enter chat screen"),
    isPresented: $showConfirmationPopup
) {
    Button("Cancel", role: .cancel) {}                    
    Button("OK") {
        print("enter screen tapped")
        // some operations
    }
} message: {
    Text("enter chat screen?")
}

I tried to wrap the "OK" button in NavigationLink but it didn't work. I tried to add NavigationLink(destination: ChatScreen()) {} under the ok button but it didn't work either.


Solution

  • You should replace the Button with a NavigationLink. And the view with the alert needs to be inside a NavigationStack.

    Here is a standalone example to show it working:

    struct ChatScreen: View {
        var body: some View {
            Text("ChatScreen")
        }
    }
    
    struct ContentView: View {
        @State private var showConfirmationPopup = false
    
        var body: some View {
            NavigationStack {
                VStack {
                    Button("Show alert") {
                        showConfirmationPopup = true
                    }
                }
                .alert(
                    Text("enter chat screen"),
                    isPresented: $showConfirmationPopup
                ) {
                    Button("Cancel", role: .cancel) {
    
                    }
                    NavigationLink("OK") {
                        ChatScreen()
                    }
                } message: {
                    Text("enter chat screen?")
                }
            }
        }
    }