🍎 iOS/SwiftUI

matchedGeometryEffect(Hero animation)

JerryiOS 2024. 8. 9. 02:55

Hero Animation


matchedGeometryEffect

식별자와 네임스페이스를 제공하여 기하학이 동기화된 뷰 그룹을 정의.

 

이 modifier를 여러 뷰에 부착하면 SwiftUI가 뷰 간의 연결을 이해하고, 자동으로 Transition을 적용할 수 있게 된다.

 

1. 기본 구조설정

@Namespace var animation

 

SwiftUI에서 Hero 애니메이션을 구현하기 위해 먼저 네임스페이스를 정의한다.


2. 뷰에 modifier 붙이기

VStack {
    if shouldAnimate { 
        Rectangle () 
          .matchedGeometryEffect(id: "shape" , in: animation) 
    } else { 
        Rectangle () 
          .matchedGeometryEffect(id: "shape" , in: animation) 
          .frame(width: 200 , height: 200 ) 
    } 
}

 

Hero 애니메이션을 구현할 뷰에 modifier를 붙인다.

3. 애니메이션 적용

VStack {

// ...

}
.onTapGesture { 
   withAnimation(.spring()) { 
       shouldAnimate.toggle() 
   } 
}

 

 


 

출처

https://mobileappcircular.com/how-to-create-a-hero-animation-in-swiftui-154c6c6980ef

 

How to create a hero animation in SwiftUI?

Using matchedGeometryEffect to impress at first glance

mobileappcircular.com

 

반응형