SwiftUI - Matched Geometry Effect Size doesn't match

Viewed 193

Consider the following sample:

struct MatchedGeometryHeight: View {
    
    @State private var mainHeight: CGFloat = 100
    @Namespace private var namespace
    
    var body: some View {
        ScrollView {
            VStack {
                VStack {
                    HStack {
                        Text("Main Height")
                        Slider(value: $mainHeight, in: 10...200)
                    }
                }.padding(.vertical, 20)
                
                RoundedRectangle(cornerRadius: 8)
                    .foregroundColor(.green.opacity(0.8))
                    .frame(height: mainHeight)
                    .matchedGeometryEffect(id: "dynamic",
                                           in: namespace)
                
                Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eleifend risus id laoreet imperdiet. Praesent molestie lectus id sem ornare ultricies. Nam faucibus ante erat.")
                    .foregroundColor(.white)
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 8)
                            .foregroundColor(.blue)
                            .shadow(radius: 2, x: 0, y: 2))
                    .matchedGeometryEffect(id: "dynamic",
                                           in: namespace,
                                           properties: .size,
                                           isSource:  false)
            }
        }
        .padding()
    }
}

This produces:

Staggered Height Changes

I'm expecting the blue rectangle to match the green one's. However, what happens instead is that the blue rectangle tightly hugs its text rather than the geometry effect.

Now, because this is a simple example, I know I could fix that by using the following modifier:

.frame(minWidth: .zero,
       maxWidth: .infinity,
       minHeight: .zero,
       maxHeight: .infinity)

Smooth Height Changes

But unfortunately in the real world, I want to be able to be able to pass generic contents to those Rectangles (think cards with varying amounts of data). When that happens, setting the .frame modifier like previously mentioned doesn't help at all.

Complex view doesn't resize

From what I see, it seem like a view will refuse using a smaller size than what its own contents require.

How can I achieve this?

0 Answers
Related