'LazyVGrid inside a VStack inside a ScrollView among other elements causes a crash

Here's my view's code:

ScrollView {
    VStack {
        someView

        LazyVGrid(
            columns: [
                GridItem(
                    .adaptive(minimum: metrics.size.width / 2),
                    spacing: 0
                )
            ],
            spacing: 0
        ) {
            ForEach(items, id: \.self) { item in
                getItemView(item)
            }
        }

        someOtherView
    }
}

This causes a crash:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
#0  0x000000011242c8d6 in specialized HVGrid.minorGeometry(updatingSize:) ()
#1  0x00000001125464fe in specialized IncrementalStack<>.sizeThatFits(proposedSize:children:context:state:) ()
#2  0x000000011254bf61 in protocol witness for IncrementalLayout.sizeThatFits(proposedSize:children:context:state:) in conformance LazyHGridLayout ()
#3  0x000000011254bee7 in protocol witness for IncrementalLayout.sizeThatFits(proposedSize:children:context:state:) in conformance LazyVGridLayout ()
#4  0x0000000112591a63 in closure #1 in IncrementalLayoutComputer.Engine.sizeThatFits(_:) ()
#5  0x0000000112591897 in IncrementalLayoutComputer.Engine.sizeThatFits(_:) ()
#6  0x0000000112bc2ec0 in LayoutComputer.EngineDelegate.sizeThatFits(_:) ()
#7  0x0000000112700ddf in _PaddingLayout.sizeThatFits(in:context:child:) ()
#8  0x00000001127012d1 in protocol witness for UnaryLayout.sizeThatFits(in:context:child:) in conformance _PaddingLayout ()
#9  0x0000000112709c95 in closure #1 in UnaryLayoutEngine.sizeThatFits(_:) ()
#10 0x0000000112709b61 in UnaryLayoutEngine.sizeThatFits(_:) ()

How can I fix this?



Solution 1:[1]

Here are 2 ways to resolve the issue. Either

  1. use LazyVStack instead of VStack

  2. or specify the width of the LazyVGrid explicitly:

    LazyVGrid(
        columns: [
            GridItem(
                .adaptive(minimum: metrics.size.width / 2),
                 spacing: 0
            )
        ],
        spacing: 0
    ) {
        ForEach(items, id: \.self) { item in
            getItemView(item)
        }
    }
    // add this
    .frame(width: metrics.size.width)
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1