gpt4 book ai didi

swiftui - 将绑定(bind)分配给容器 View

转载 作者:行者123 更新时间:2023-12-04 08:27:18 26 4
gpt4 key购买 nike

我无法将绑定(bind)值分配给 MyContainer因为我得到“无法将'Binding'类型的值分配给'Bool'类型”并且无论我探索了多少次迭代都无法通过它。
我有一个 TestingContainer我在其中声明 showContainer 的结构我在按钮中使用的 -> 并且我希望该值达到 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")
})
}
}
}
}

然后我有一个 MyContainer我希望能够更改 showContainer 的 View 值,但我得到了前面提到的错误。
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))

}

}
}
你能帮我找出我的错误吗?
谢谢!

最佳答案

应该是这样的

init(show: Binding<Bool>, @ViewBuilder content: () -> Content) {
self.content = content()
self._showContainer = show
}
@Binding是一个属性包装器,它自己的自动生成的存储属性以带有下划线的规范为前缀。
注意:您可以直接访问绑定(bind)属性,即
Color.black.opacity(self.showContainer ? 0.1 : 0).edgesIgnoringSafeArea(.all)

关于swiftui - 将绑定(bind)分配给容器 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65198621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com