iosswiftuiswiftui-navigationlinkswiftui-actionsheet

How to navigate out of a ActionSheet?


how to navigate out of a ActionSheet where I can only Pass a Text but not a NavigationLink?

Sample Code:

struct DemoActionSheetNavi: View {
    @State private var showingSheet = false

    var body: some View {
        NavigationView {

            Text("Test")

            .actionSheet(isPresented: $showingSheet) {
                ActionSheet(
                    title: Text("What do you want to do?"),
                    message: Text("There's only one choice..."),
                    buttons: [
                        .default(Text("How to navigate from here to HelpView???")),
                ])
            }


        }
    }
}

Solution

  • You would need something like this:

    struct DemoActionSheetNavi: View {
    
        @State private var showingSheet = false
        @State private var showingHelp = false
    
        var body: some View {
            NavigationView {
                VStack {
                    Text("Test")
                    Button("Tap me") { self.showingSheet = true }
                    NavigationLink(destination: HelpView(isShowing: $showingHelp),
                                   isActive: $showingHelp) {
                        EmptyView()
                    }
                }
                
            }
            .actionSheet(isPresented: $showingSheet) {
                ActionSheet(
                    title: Text("What do you want to do?"),
                    message: Text("There's only one choice..."),
                    buttons: [.cancel(),
                              .default(Text("Go to help")) {
                                self.showingSheet = false
                                self.showingHelp = true
                        }])
            }
            
            
        }
    }
    

    You have another state that programmatically triggers a NavigationLink (you could also do it using .sheet and modal presentation). You would also need to pass showingHelp as a @Binding to help view to be able to reset it.

    struct HelpView: View {
        
        @Binding var isShowing: Bool
    
        var body: some View {
            Text("Help view")
                .onDisappear() { self.isShowing = false }
            
        }
        
    }