2

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?

chrispsv
  • 503
  • 1
  • 3
  • 21

1 Answers1

2

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())
    }
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • The use of the `if` statement is cool. I would never think it out myself. Most of the posts I found use `EmptyView`. But Apple's doc says that view should be rarely needed. That's why I tried to look for a better approach and stumbled on here. In my opinion, for a common scenario like navigating to another view from action sheet, both approaches are not ideal. Hope Apple will work out a better way in future. – rayx Jan 17 '22 at 13:47
  • Unfortunately after actually trying the approach I find it has an issue when animation is enabled. The `NavigationLink` view shows in the original view during the transition. So it seems using `EmptyView` is the right way to go. – rayx Jan 18 '22 at 02:59