swiftswiftuivstacklazyhgrid

Why is LazyHGrid not as high as its items?


I've got a LazyHGrid that shows multiple Text views in one row. That LazyHGrid is inside a VStack. However, the LazyHGrid is higher than it needs to be. What causes the extra 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)
        }
    }
}

enter image description here


Solution

  • You just have to add .fixedSize() modifier to your grid, and it works...

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

    With fixedSize()