3
votes

I have a View 'B' that has an initialiser that takes an argument.

struct B: View {
    let arg: Int

    init(arg: Int) {
        self.arg = arg
    }

    var body: some View {
        Text("\(arg)")
    }
}

And I have a Navigation View 'A'.

'A' has one button, which when pressed, shows a popup where the user picks a number from 1-5. A closure of type (Int) -> Void is called with the chosen number.

struct A: View {
    @State var showPicker = false

    var body: some View {
        NavigationView {
            Button(action: { self.showPicker = true }) {
                Text("Pick Number")
            }
            .sheet(isPresented: self.$showPicker, content: { 
                NumberPicker { number in 
                    *** Possible to navigate to B from here? ***
                } 
            })
        }
    }
}

Question
Is it possible to initialise view B with the result from the closure, and then navigate to it?

This used to be possible with DynamicNavigationDestinationLink, however Apple deprecated it and stated in the release notes that NavigationLink contains its capabilities now. I have searched through the docs, however, I have not been able to figure out how to use NavigationLink to produce the same outcome.

1

1 Answers

0
votes

You need to add a new view with another navigationview where you can pick the number.

Here's a full code example how i would approach this:

import SwiftUI

struct viewA: View {

    var body: some View {
        NavigationView {
            NavigationLink(destination: viewC()) {
                Text("Pick Number")
            }
        }
    }
}

struct viewB: View {

    @Binding var showSheet: Bool
    @Binding var arg: Int

    var body: some View {
        NavigationView {
            List {
                ForEach((1...5), id: \.self) {number in
                    Button(action: {
                        self.arg = number
                        self.showSheet.toggle()
                    }) {
                        Text("\(number)")
                    }
                }
            }
        }
    }
}

struct viewC: View {

    @State var showSheet:Bool = true
    @State var arg: Int = 0

    var body: some View {
        NavigationView {
            Text("\(arg)")
        }
        .sheet(isPresented: $showSheet) {
            viewB(showSheet: self.$showSheet, arg: self.$arg)
        }
    }
}