0
votes

I'm an absolute beginner, so please indulge me. I have looked at a number of answers, both in Stack Overflow and elsewhere, that I thought might give me a solution, but none seem to work.

What I really want to do is transfer the value of a computed variable from one view to another.

As a poor alternative, because it would take a lot of rework, I could transfer the values of the variables the computation works on to the second view (a sheet is preferred, but I could use juts another view) and do the computation there instead.

I have tried binding, ObservableObject, Observed var, Published var, but none seem to work.

The base variables used for the computation are derived from a list view in the first view using @State, so each variable is a @State var. There are seven variables each with its own array.

2

2 Answers

0
votes

Here is an example if you don't want to change the value in the DetailView:

struct ContentView: View {
    @State private var currentCount = 0

    var body: some View {
        NavigationLink(destination: DetailView(count: currentCount)) {
            Text("Tap Here!")
        }
    }
}

struct DetailView: View {
    var count: Int

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

Here is an example if you want to change make the value changeable from the DetailView. You need to use @Binding in this case:

struct ContentView: View {
    @State private var currentCount = 0

    var body: some View {
        VStack {
            Text("\(currentCount)")

            NavigationLink(destination: DetailView(count: $currentCount)) {
                Text("Tap Here!")
            }
        }
    }
}

struct DetailView: View {
    @Binding var count: Int

    var body: some View {
        VStack {
            Text("\(count)")

            Button(action: {
                self.count += 1
            }) {
                Text("Increase!")
            }
        }
    }
}
0
votes

Here is the simplest way to do this for just one variable at a time. To do more, follow an entire tutorial on ObservedObject until you grasp that concept. I can’t make an app without ObservedObject. Or I can, but it’s like tying one hand behind my back. Anyway, for one:

In the subview, write the variable like this:

@Binding var passedDownList: [Item]

Then you call the sub view using the $ syntax like for text field and stuff.

MySubView(passedDownList: $myList)

There. The array will be in sync between the two views.