Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65928481/how-do-i-pass-a-state-binding-to-the-content-closure-of-a-custom-container

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...