import SwiftUI
struct MatchedGeometryEffectDemo: View {
@Namespace private var animationNamespace
@State private var isToggled = false
var body: some View {
HStack {
if !isToggled {
Color.blue
.frame(width: 100, height: 100)
.matchedGeometryEffect(id: "square", in: animationNamespace)
.onTapGesture {
isToggled.toggle()
}
Spacer()
Color.red
.frame(width: 100, height: 100)
} else {
Color.red
.frame(width: 100, height: 100)
Spacer()
Color.blue
.frame(width: 100, height: 100)
.matchedGeometryEffect(id: "square", in: animationNamespace)
.onTapGesture {
isToggled.toggle()
}
}
}
.padding()
.animation(.easeInOut, value: isToggled)
}
}
struct MatchedGeometryEffectDemo_Previews: PreviewProvider {
static var previews: some View {
MatchedGeometryEffectDemo()
}
}This code uses matchedGeometryEffect to link the blue square's position and size between two places in the layout. When you tap the blue square, the isToggled state changes, switching the squares' positions. The matchedGeometryEffect with the same id and Namespace makes the blue square animate smoothly from one side to the other. The red square stays static. The animation uses .easeInOut for a smooth effect.
This is like moving a toy block from one hand to another, and you see it glide smoothly instead of jumping.