사용하기 전과 후 차이점

 

위에서 보듯이 사용하게 되면 뷰의 변화에 대해 더 부드럽게 대응하는 UI를 만들 수 있습니다.

matchedGeometryEffect는 같은 뷰로 인식할 고유한 id 값과 이 정보를 기억할 @Namespace 프로퍼티 래퍼를 사용해야 합니다.

 

사용 방법

struct ContentView: View {
    let categories: [String] = ["Home", "popular", "Saved"]
    @State private var selected: String = ""
    @Namespace private var namespace
    
    var body: some View {
        HStack {
            ForEach(categories, id: \.self) { category in
                ZStack(alignment: .bottom) {
                    if selected == category {
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.red.opacity(0.5))
                            .matchedGeometryEffect(id: "category_background", in: namespace)
                            .frame(width: 35, height: 2)
                            .offset(y: 10)
                    }
                    
                    Text(category)
                        .foregroundStyle(selected == category ? .red : .white)
                }
                .frame(maxWidth: .infinity)
                .frame(height: 55)
                .onTapGesture {
                    withAnimation(.spring()) {
                        selected = category
                    }
                }
            }
        }
    }
}

 

 

 

 

ytw_developer