Home > Back-end >  SwiftUI - Passing a variable up through View Hierarchy and back down again?
SwiftUI - Passing a variable up through View Hierarchy and back down again?

Time:01-12

I apologize if my question is not worded correctly.

I have 3 views: 1) ContentView, which has a TabView leading to 2) NestedView, which has a popup view that darkens the screen behind it called 3) SelectView

Here is the necessary code for ContentView. I have a TabView leading to NestedView and a condition to darken and blur the background when darken is true.

 TabView (selection: $selection){
                
                NestedView()
                    .tabItem {
                        selection == 0 ? Image(systemName: "house.fill") : Image(systemName: "house")
                    }
                    .tag(0)   
            }   
            if darken {
                ZStack {
                    ZStack {
                        Rectangle()
                            .ignoresSafeArea(.all)
                            .foregroundColor(Color.black).opacity(0.75)
                    }.background(Blur(style: .systemChromeMaterial).opacity(0.85)
                        .ignoresSafeArea(.all))
                    SelectView(darken: $darken)
                }

I want to pass in data to the SelectView constructor, but I'm not sure how to get the data there.

Here is the code for NestedView

    @State var dataArray: [ItemDataModel]
    @Binding var darken: Bool

Button(action: {
                darken = true
            }) {

I need dataArray to be sent through the SelectView constructor in ContentView.

In SelectView I have a Binding variable for darken, and I know I need another for the received data, but I'm not sure whether it needs to be @State or @Binding or something entirely different.

@Binding var darken: Bool
@________ var dataArray: [ItemDataModel]

Any help is appreciated!

CodePudding user response:

NestedView should not have a @State var dataArray: [ItemDataModel].

NestedView and SelectView should both have a @Binding var dataArray: [ItemDataModel].

You should move @State var dataArray: [ItemDataModel] up into ContentView so it can pass $dataArray down to both NestedView and SelectView.

  • Related