首页 > 解决方案 > 如何在 SwiftUI 中转换动画?

问题描述

在这里,我得到了 2 个形状,一个 Rectangle 和一个 Circle,通过 Button 的操作,其中只有一个对用户可见,我尝试使用 @Namespace 进行此转换,但没有成功!

我的目标:从一个 Shape 到另一个 Shape 的转换动画非常流畅。

在此处输入图像描述

struct ContentView: View {

@State var action: Bool = false
@Namespace var sameShape

var body: some View {
    
    
    ZStack
    {
        
        Group
        {
            if action
            {
                Circle()
                    .fill(Color.blue).frame(width: 150, height: 150, alignment: .center)
                    .matchedGeometryEffect(id: "Dakota148Zero", in: sameShape)
            }
            else
            {
                Rectangle()
                    .fill(Color.red).frame(width: 150, height: 150, alignment: .center)
                    .matchedGeometryEffect(id: "Dakota148Zero", in: sameShape)
            }
        }
        .animation(.easeInOut)
        
        
        
        VStack
        {
            
            Spacer()
            
            Button("transform") { action.toggle() }.font(Font.largeTitle).padding()
            
        }
        
    }
    
    
    }
}

标签: swiftui

解决方案


Group不是真正的容器,所以不要存储动画。Group用一些堆栈替换,比如

        VStack
        {
            if action
              // ... other code no change

推荐阅读