How do I pass a @State binding to the Content closure of a custom container?

801 Views Asked by At

I'm starting to play with custom containers and I'm stuck trying to send the @State var across. Sample code:

struct ZoomCardView<Content: View>: View {
    let contentDefault: ((Binding<Bool>)) -> Content
    let contentZoomed: (Binding<Bool>) -> Content
    
    init(@ViewBuilder defaultContent: @escaping (Binding<Bool>) -> Content, @ViewBuilder zoomed: @escaping (Binding<Bool>) -> Content) {
        self.contentDefault = defaultContent
        self.contentZoomed = zoomed
    }
    
    @State private var isShowing: Bool = false
    
    var body: some View {
        HStack {
            if isShowing {
                self.contentZoomed($isShowing)
                    .transition(.scale(scale: 0, anchor: .center))
            } else {
                self.contentDefault($isShowing)
                    .transition(.scale(scale: 0, anchor: .center))
            }
        }
    }
}

The idea is that the callsite would render the content and provide the mechanism to toggle the isShowing var. The rationale is to allow the callsite to decide which gesture or UI element controls the toggle:

struct ContentView: View {
    var body: some View {
        ZoomCardView { isShowing in
            Button(action: {
                isShowing.toggle()  <---- *** Error (see below)
            }, label: {
                Text("Open")
            })
        } zoomed: { isShowing in
            Button(action: {
                isShowing.toggle()  <---- *** Error (see below)
            }, label: {
                Text("Zoomed")
            })
        }
        .frame(width: 300, height: 300)
        .cornerRadius(15)
        .shadow(radius: 5)
    }
}

The issue: I get a Cannot call value of non-function type 'Binding<() -> ()> in the two isShowing.toggle() lines above. I'm not sure why. Any ideas?

0

There are 0 best solutions below