0
0
iOS Swiftmobile~5 mins

matchedGeometryEffect in iOS Swift

Choose your learning style9 modes available
Introduction

The matchedGeometryEffect helps you smoothly move or transform a view from one place to another in your app. It makes animations look natural and connected.

When you want to animate a button moving to a new position on the screen.
When you want to smoothly change a small image into a larger one on tap.
When you want to animate a card expanding from a list to a detail view.
When you want to connect two views visually during a transition.
Syntax
iOS Swift
view.matchedGeometryEffect(id: "uniqueID", in: namespace)

The id is a unique string or value that links two views together.

The namespace is a special container that groups matched views for animation.

Examples
This links a Text view with the id "text" inside the given namespace.
iOS Swift
Text("Hello")
  .matchedGeometryEffect(id: "text", in: namespace)
This links a Circle shape with the id "circle" for animation.
iOS Swift
Circle()
  .frame(width: 50, height: 50)
  .matchedGeometryEffect(id: "circle", in: namespace)
Sample App

This example shows a blue rounded rectangle that grows from a small square to a large square when tapped. The matchedGeometryEffect links the two shapes so the animation is smooth and connected.

iOS Swift
import SwiftUI

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

  var body: some View {
    VStack {
      if !isExpanded {
        RoundedRectangle(cornerRadius: 25)
          .fill(Color.blue)
          .frame(width: 100, height: 100)
          .matchedGeometryEffect(id: "shape", in: namespace)
          .onTapGesture {
            withAnimation(.spring()) {
              isExpanded = true
            }
          }
      } else {
        RoundedRectangle(cornerRadius: 25)
          .fill(Color.blue)
          .frame(width: 300, height: 300)
          .matchedGeometryEffect(id: "shape", in: namespace)
          .onTapGesture {
            withAnimation(.spring()) {
              isExpanded = false
            }
          }
      }
    }
  }
}
OutputSuccess
Important Notes

Always use the same id and namespace for views you want to animate between.

The views must be in the same view hierarchy or visible at the same time for the effect to work.

You can animate many properties like size, position, and shape with this effect.

Summary

matchedGeometryEffect links two views for smooth animations.

Use a unique id and a shared namespace to connect views.

Great for animating changes in size, position, or shape between views.