屏幕底部的 SwiftUI 动画无法正常工作

Seb*_*ian 6 swiftui swiftui-animation xcode14

我正在尝试创建一个从底部进入屏幕的视图的动画。但第一次它只出现在屏幕上,没有任何动画,然后它就开始正常工作。

这是代码:

struct ContentView: View {
@State private var showView = false
var body: some View {
    ZStack(alignment: .bottom){
        VStack{
            Button("TAP HERE") {
                withAnimation(.spring()) {
                    showView.toggle()
                }
            }
            Spacer()
        }
        if showView {
            RoundedRectangle(cornerRadius: 30)
                .frame(height: UIScreen.main.bounds.height * 0.5)
                .transition(.move(edge: .bottom))
        }
    }
    .edgesIgnoringSafeArea(.bottom)
}
Run Code Online (Sandbox Code Playgroud)

}

这是行为:

在此输入图像描述

我做错了什么?

我正在使用 Xcode 14 beta 5 和 Swift 5

Bog*_*oga 0

实际上,我认为你只需要把spring效果移到RoundedRectangle.

struct ContentView: View {
    @State private var showView = false
    var body: some View {
        ZStack(alignment: .bottom){
                VStack{
                    Button("TAP HERE") {
                        withAnimation {
                            showView.toggle()
                        }
                    }
                    Spacer()
                }
                if showView {
                    RoundedRectangle(cornerRadius: 30)
                        .frame(height: UIScreen.main.bounds.height * 0.5)
                        .transition(.move(edge: .bottom))
                        .animation(.spring(), value: showView)
                }
            }
            .edgesIgnoringSafeArea(.bottom)
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Xcode 中,动画有点奇怪,但在模拟器中它工作正常。