swiftuiswiftui-navigationlinkactionsheet

using Navigationlink in actionsheet swiftui


Does anyone know how I can go to another view from an actionsheet in Swiftui?

Currently I use this as a button in actionsheet:

.actionSheet(isPresented: $actionsheet) {
    ActionSheet(title: Text("Actions"), message: Text("Choose action"), buttons: [
        .default(
            NavigationLink(destination: adddetails()) {
                Text("Add details")
            }
        ),
        .default(Text("New")),
        .default(Text("Delete")),
        .cancel()
    ])                              
}

But it won't build. Even though Xcode doesn't give me an error. Does anyone know what I can do?


Solution

  • You can control a NavigationLink programmatically by using the isActive parameter with a binding. Then, in your ActionSheet, you can toggle that binding.

    The other key is that the NavigationLink needs to be embedded in your original view hierarchy and not the ActionSheet. You can conditionally display it with an if statement so that it's only there if active (and thus invisible unless the navigate button is pressed):

    struct ContentView: View {
        @State private var actionSheetOpen = false
        @State private var navigationLinkActive = false
        
        var body: some View {
            NavigationView {
                if navigationLinkActive {
                    NavigationLink("", destination: Text("Detail"), isActive: $navigationLinkActive)
                }
                
                Button("Open action sheet") {
                    actionSheetOpen.toggle()
                }
                .actionSheet(isPresented: $actionSheetOpen) {
                    ActionSheet(title: Text("Actions"), message: Text("Choose action"), buttons: [
                        .default(Text("Navigation"), action: {
                            navigationLinkActive = true
                        }),
                        .default(Text("New")),
                        .default(Text("Delete")),
                        .cancel()
                    ])
                }
                
            }.navigationViewStyle(StackNavigationViewStyle())
        }
    }