Sobes.tech
Middle+

What is matchedGeometryEffect and how is it used in SwiftUI?

sobes.tech AI

Answer from AI

matchedGeometryEffect in SwiftUI is used to create smooth animations for transitions between two views that represent the same visual element in different layouts. It links the geometry of a view in one state with the geometry of another view in a different state, allowing SwiftUI to automatically animate changes.

It is used by applying the .matchedGeometryEffect modifier to both views that should be linked. The modifier takes three parameters:

  1. id: A unique identifier for the linked views.
  2. in: The namespace in which the identifier is registered. Usually created with @Namespace.
  3. properties: A set of geometry properties to be animated (e.g., .position, .size, .frame).

Example usage:

struct ContentView: View {
    @Namespace private var animation
    @State private var isExpanded = false

    var body: some View {
        VStack {
            if isExpanded {
                Rectangle()
                    .fill(Color.blue)
                    .matchedGeometryEffect(id: "myShape", in: animation)
                    .frame(width: 200, height: 200)
                    .onTapGesture {
                        withAnimation {
                            isExpanded.toggle()
                        }
                    }
            } else {
                Rectangle()
                    .fill(Color.red)
                    .matchedGeometryEffect(id: "myShape", in: animation)
                    .frame(width: 50, height: 50)
                    .onTapGesture {
                        withAnimation {
                            isExpanded.toggle()
                        }
                    }
            }
        }
    }
}

In this example, .matchedGeometryEffect links two Rectangles with the same id ("myShape") and in the same namespace (animation). When isExpanded toggles, SwiftUI animates the transition between the two view states, creating a smooth effect of size and position change of the rectangle.

What is matchedGeometryEffect and how is it used in… - sobes.tech