I'm wondering why my matchedGeometryEffect isn't working as expected. Did I do something wrong? Because this guy (at 3:15) did the same and it looks much smoother. Im running the code on a M1 MacBook Air that means the speed is probably not the problem. Here is my Code:

struct ContentView: View {
    @Namespace var namespace
    @State var bool = true
    var body: some View {
        HStack{
            if bool {
                Rectangle()
                    .frame(width: 100, height: 100)
                    .foregroundColor(Color.red)
                    .padding()
                    .onTapGesture {
                        withAnimation(.spring(response: 0.5, dampingFraction: 0.7)){
                            bool.toggle()
                        }
                    }
                    .matchedGeometryEffect(id: "id", in: namespace)
            } else {
                Rectangle()
                    .frame(width: 200, height: 200)
                    .foregroundColor(Color.red)
                    .matchedGeometryEffect(id: "id", in: namespace)
            }
        }
    }
}

Thanks for your help, Boothosh

score:3

In SwiftUI, the modifier order matters. This is the same with matchedGeometryEffect(id:in:properties:anchor:isSource:).

If you want the rectangles to expand in the center, you need the geometries to align in the center. To do this, we will have Rectangles of the same size. This means that both Rectangles will have the matchedGeometryEffect modifier attached, and then styled after.

Code:

HStack {
    if bool {
        Rectangle()
            .matchedGeometryEffect(id: "id", in: namespace) // <- Here
            .frame(width: 100, height: 100)
            .foregroundColor(Color.red)
            .padding()
            .onTapGesture {
                withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) {
                    bool.toggle()
                }
            }
    } else {
        Rectangle()
            .matchedGeometryEffect(id: "id", in: namespace) // <- Here
            .frame(width: 200, height: 200)
            .foregroundColor(Color.red)
    }
}

More questions