断断续续的动画 SwiftUI 嵌套视图

Choppy Animation SwiftUI Nested Views

我正在制作一个动画,该动画从屏幕底部调出一个视图,位于之前占据屏幕的部分视图上方。我的代码在技术上是可行的,但我担心动画看起来太不稳定了。基本上,我认为正在发生的事情是,新的、上升的视图由其他几个视图组成,当我为它的出现设置动画时,它也会为汇集在一起​​的子视图设置动画——这是我不喜欢的样子。

示例代码:

struct ButtonView: View {
    @State var show: Bool = false
    var body: some View {
        ZStack{
            VStack {
                Button(action: { withAnimation(.linear(duration: 0.5)) { show = !show }} )  {
                    Text("Press Me")
                }
                Rectangle()
                    .foregroundColor(.gray)
            }
        }
        if show {
            VStack {
                CollapsibleView()
            }
        }
    }
}

struct CollapsibleView: View {
    var body: some View {
        ZStack {
            VStack {
                Text("Text 1")
                Text("Text 2")
                Text("Text 3")
            }
            .background(Color.white)
        }
    }
}

请注意,出于说明目的,持续时间设置得相当长,但即使持续时间值较小,我仍然可以注意到断断续续的效果。

如何避免这种情况?有没有办法让动作动起来?

这里有一个方法可以满足您的需求:

struct ContentView: View {
    
    @State var show: Bool = Bool()
    
    var body: some View {
        
        VStack {
            
            Button(action: { show.toggle() }, label: { show ? Text("hide") : Text("show") })
                .animation(nil)
            
            Color.gray
            
            Group {
                
                if show { CollapsibleView().transition(.asymmetric(insertion: .move(edge: .bottom), removal: .move(edge: .bottom))) }
                
            }
            .opacity(show ? 1.0 : 0.0)
            
        }
        .animation(Animation.spring(response: 0.4, dampingFraction: 0.4, blendDuration: 1.0), value: show)
        
        
    }
}

struct CollapsibleView: View {
    var body: some View {
        
        VStack(alignment: .leading) {
            Text("Text 1")
            Text("Text 2")
            Text("Text 3")
        }
        .background(Color.white)
        
    }
}