Assigning Binding to a container view

Viewed 189

I'm having trouble with assigning binding value to MyContainer as I get "Cannot assign value of type 'Binding' to type 'Bool'" and cannot get through it no matter how much iterations I've explored.

I have a TestingContainer struct in which I declare showContainer that I use in a button -> and I want that value to get to MyContainer.

struct TestingContainer: View {
    @State private var showContainer = false
    
    var body: some View {
        VStack {
            MyContainer(show: $showContainer) {
                VStack {
                    ForEach(0 ..< 5) { item in
                        Text("Hi!")
                    }
                }
            }
            if showContainer == false {
                Button(action: {showContainer = true}, label: {
                    Text("Show Container")
                })
            }
        }
    }
}

Then I have a MyContainer view from which I want to be able to change the showContainer value but I get the before-mentioned error.

struct MyContainer<Content: View>: View {
    let content: Content
    @Binding var showContainer: Bool
    
    init(show: Binding<Bool>, @ViewBuilder content: () -> Content) {
            self.content = content()
            self.showContainer = show
        }
    
    var body: some View {
        ZStack {
            Color.black.opacity($showContainer.wrappedValue ? 0.1 : 0).edgesIgnoringSafeArea(.all)
                .onTapGesture {
                    self.showContainer = false
                }
                .overlay(
                    self.content
                        .frame(width: 350, height: 450)
                        .background(Color.white))
        
        }
        
    }
}

Can you please help me find my mistake?

Thank you!

1 Answers

Here is how it should be

init(show: Binding<Bool>, @ViewBuilder content: () -> Content) {
        self.content = content()
        self._showContainer = show
    }

@Binding is a property wrapper and its own autogenerated stored property is prefixed by specification with underscore.

Note: you can access bound property directly, i.e.

Color.black.opacity(self.showContainer ? 0.1 : 0).edgesIgnoringSafeArea(.all)
Related