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:
-
Defining
idand animation namespace:- Assign a unique
idto all views that should be synchronized, using thematchedGeometryEffectmodifier. - Specify a
namespace(animation namespace). Thenamespacelinks views that should be animated together. Typically, this is declared with@Namespace private var namespace.
- Assign a unique
-
Applying to views:
- Apply
matchedGeometryEffectto each view involved in the animation, specifying the sameidandnamespace. - Change the visibility or position of views, for example, using
if/elseconditions or changing state that affects layout. SwiftUI automatically animates the transition.
- Apply
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
idandnamespacefor 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.