【发布时间】:2023-02-25 09:49:48
【问题描述】:
我正在创建一个可重复使用的自下而上面板,其中自下而上面板内显示的视图会有所不同。我还希望这个面板成为一个视图修改器。我过去创建过视图修饰符,但从未将视图作为视图修饰符内容传递。当我尝试通过视图时,出现如下所述的错误。
查看修改后的代码:
struct BottomPanel: ViewModifier {
@Binding var isPresented: Bool
let panelContent: Content
init(isPresented: Binding<Bool>, @ViewBuilder panelContent: @escaping () -> Content) {
self.panelContent = panelContent()
self._isPresented = isPresented
}
func body(content: Content) -> some View {
content.overlay(self.$isPresented.wrappedValue ? bottomPanelContent() : nil)
}
@ViewBuilder
private func bottomPanelContent() -> some View {
GeometryReader { geometry in
VStack(spacing: 0) {
self.panelContent
}
// some modifiers to change the color or height of the panel.
}
}
}
查看扩展:
extension View {
func bottomPanel(isPresented: Binding<Bool>, @ViewBuilder panelContent: @escaping () -> BottomPanel.Content) -> some View {
return modifier(BottomPanel(isPresented: isPresented, panelContent: panelContent)
}
}
我希望在自下而上面板中打开的内容视图和子视图:
struct ContentView: View {
@State var showBottomPanel: Bool = false
var body: some View {
VStack {
Button(action: { self.showBottomPanel = true}) {
Text("Click me to open bottom panel")
}
}
.bottomPanel(isPresented: $self.showBottomPanel, panelContent: { ChildView() })
}
}
struct ChildView: View {
var body: some View {
VStack {
Button("Click Me 1", action: {}).foregroundColor(.blue)
Button("Click Me 2", action: {}).foregroundColor(.red)
}
}
}
错误:Cannot convert value of type 'ChildView' to closure result type 'BottomPanel.Content' (aka '_ViewModifier_Content<BottomPanel>')。
我究竟做错了什么?如何将视图传递给 BottomPanel?
注意:我已经从底部面板中删除了很多代码以保持代码发布简短,但如果需要它,请告诉我,我可以分享。
谢谢阅读!
【问题讨论】: