Make view with matchedGeometryEffect claim space in ScrollView

40 Views Asked by At

I have multiple views in a ScrollView and I want one of them to size itself by the dimensions of another view. Luckily .matchedGeometryEffect offers the option to only match the size between views instead of the entire frame.

Visually this works, but mechanically there is an issue. The view that matches the size doesn't expose the proper content size to the ScrollView. This causes the placement of following views to ignore the matched size. And the scrollable content size does not adjust either. How do I fix that? Is that a SwiftUI bug?

Also, the matching box is placed weirdly, but that is not a real issue for what I need to achieve in the end. However that might be related to the problem.

I created a simple example that demonstrates the issue:

struct TestView: View {
    @Namespace var namespace

    var body: some View {
        ScrollView {
            VStack(spacing: 0) {
                // Source view
                Color.red.frame(width: 200, height: 300)
                    .matchedGeometryEffect(id: "match", in: namespace, properties: .size, isSource: true)

                // This view matches the size of the previous view
                Color.gray
                    .matchedGeometryEffect(id: "match", in: namespace, properties: .size, isSource: false)

                Text("This text should be directly below the gray box")
                // But it isn't :(
            }
        }
    }
}

example screenshot

0

There are 0 best solutions below