ios 带有滚动视图问题的SwiftUI LazyVGrid

vnjpjtjt  于 2023-05-30  发布在  iOS
关注(0)|答案(1)|浏览(207)

文本“底部文本”旨在占据底部的一些空间。然而,当使用带有滚动视图的LazyVGrid时,内容最终会呈现在底部文本后面,并且可滚动区域看起来会延伸到屏幕之外。
如何解决这个问题?

预期

实际

struct HFlexibleView<Content: View>: View {
    let triggerWidth: CGFloat
    let content: () -> Content
    ///If this is set true, the view will be rendered normally, insead of being arranged flexibly
    var disabled: Bool
    var maxmumWidth: CGFloat
    var columns: [GridItem] {
        [GridItem(.adaptive(minimum: triggerWidth,
                            maximum: maxmumWidth))]
    }
    
    init(triggerWidth: CGFloat,
         maxmumWidth: CGFloat = .infinity,
         disabled: Bool = false,
         @ViewBuilder content: @escaping () -> Content) {
        self.triggerWidth = triggerWidth
        self.maxmumWidth = maxmumWidth
        self.disabled = disabled
        self.content = content
    }

    var body: some View {

        if disabled {
            content()
        } else {
            GeometryReader { geometry in
                LazyVGrid(columns: columns) {
                    content()
                        .frame(maxWidth: .infinity)
                }

            }
        }
        
    }
}

struct FlexbibleView_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            HFlexibleView(triggerWidth: 500) {
                ScrollView {
                    ForEach(0...20, id: \.self) {_ in
                        Image(systemName: "keyboard")
                            .font(.system(size: 30))
                            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 50)
                            .background(Color.green)
                            .cornerRadius(10)
                    }
                }
            }
            Text("Bottom Text")
        }
        
    }
}
hujrc8aj

hujrc8aj1#

LazyVGrid的文档说:一个容器视图,将其子视图排列在垂直增长的网格中,只在需要时创建项目。
因此,您可以使用特定的大小来约束content(即ScrollView),例如:

GeometryReader { geometry in
     LazyVGrid(columns: columns) {
         content()
             .frame(maxWidth: .infinity, maxHeight: geometry.size.height)
     }
 }

相关问题