Sobes.tech
Middle

What is matchedGeometryEffect and how to use it in SwiftUI?

sobes.tech AI

Answer from AI

matchedGeometryEffect is a modifier in SwiftUI that allows smooth animation of size and position changes of a view when transitioning between different states or view hierarchies. It synchronizes the geometry (size and position) of views across different parts of the hierarchy, creating a "matching" effect.

Usage:

  1. Defining id and animation namespace:

    • Assign a unique id to all views that should be synchronized, using the matchedGeometryEffect modifier.
    • Specify a namespace (animation namespace). The namespace links views that should be animated together. Typically, this is declared with @Namespace private var namespace.
  2. Applying to views:

    • Apply matchedGeometryEffect to each view involved in the animation, specifying the same id and namespace.
    • Change the visibility or position of views, for example, using if/else conditions or changing state that affects layout. SwiftUI automatically animates the transition.
struct ContentView: View {
    @Namespace private var animationNamespace // Declare namespace
    @State private var isExpanded = false

    var body: some View {
        VStack {
            if isExpanded {
                RoundedRectangle(cornerRadius: 10)
                    .fill(Color.blue)
                    .matchedGeometryEffect(id: "myShape", in: animationNamespace) // Apply with id and namespace
                    .frame(width: 300, height: 200)
            } else {
                RoundedRectangle(cornerRadius: 10)
                    .fill(Color.red)
                    .matchedGeometryEffect(id: "myShape", in: animationNamespace) // Apply with same id and namespace
                    .frame(width: 50, height: 50)
            }

            Button("Toggle Size") {
                withAnimation { // Use withAnimation for smooth transition
                    isExpanded.toggle()
                }
            }
        }
    }
}

Key points:

  • Same id and namespace for matching views.
  • Changes should occur within an animation block (e.g., with withAnimation).
  • Enables creating complex transitions between different layout states.
  • Can be used with various modifiers affecting size and position (frame, padding, offset, etc.).

matchedGeometryEffect greatly simplifies creating complex view transformation animations compared to manually calculating and animating frame parameters.

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