为什么 LazyHGrid 没有它的项目那么高?

Why is LazyHGrid not as high as its items?

我有一个在一行中显示多个文本视图的 LazyHGrid。 LazyHGrid 位于 VStack 中。但是,LazyHGrid 比它需要的要高。是什么导致了额外的 space?

struct ContentView: View {

    let rows = [GridItem()]

    var body: some View {
        VStack {
        
            ScrollView(.horizontal) {
                LazyHGrid(rows: rows) {
                    ForEach(0..<10) { index in
                        Text("Test \(index)")
                            .padding()
                            .foregroundColor(Color.white)
                            .background(Color.black)
                    }
                }
            }
            .background(Color.green)
        
            ScrollView(.vertical) {
                VStack {
                    ForEach(0..<100) { index in
                        Text(String(index))
                            .frame(maxWidth: .infinity)
                    }
                }
            }
            .background(Color.blue)
        }
    }
}

有效:读取带有 GeometryReader

叠加层的单元格的高度
struct ContentView: View {
    
    let rows = [ GridItem() ]
    @State private var contentSize = CGFloat.zero
    
    var body: some View {
        VStack {
            
            ScrollView(.horizontal) {
                LazyHGrid(rows: rows) {
                    ForEach(0..<10) { index in
                            Text("Test \(index)")
                                .padding()
                                .foregroundColor(.white)
                                .background(.black)
                            
                                .overlay(
                                    GeometryReader { geo in
                                        Color.clear.onAppear {
                                            contentSize = geo.size.height
                                        }
                                    }
                                )

                    }
                }
            }
            .frame(height: contentSize + 20)
            .background(Color.green)
            
            ScrollView(.vertical) {
                VStack {
                    ForEach(0..<100) { index in
                        Text(String(index))
                            .frame(maxWidth: .infinity)
                    }
                }
            }
            .background(Color.blue)
        }
    }
}

您只需将 .fixedSize() 修改器添加到您的网格中,它就会起作用...

                LazyHGrid(rows: rows) {
                    ForEach(0..<10) { index in
                        Text("Test \(index)")
                            .padding()
                            .foregroundColor(Color.white)
                            .background(Color.black)
                    }
                }
                .fixedSize()