3

I'm trying to create an animation of a View coming into the screen from the bottom. But in the very first time it only appears on screen without any animation and then it starts work properly.

This is the code:

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)
}

}

This is the behavior:

enter image description here

What I'm doing wrong?

I'm using Xcode 14 beta 5 and Swift 5

Sebastian
  • 6,154
  • 5
  • 33
  • 51

3 Answers3

1

try this:

if showView {
      RoundedRectangle(cornerRadius: 30)
          .frame(height: UIScreen.main.bounds.height * 0.5)
          .transition(.move(edge: .bottom))
          .zIndex(1) <-- here
}
wuz-good
  • 11
  • 1
0

Actually, i think that you just need to move the spring effect to the 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)
    }
}

In Xcode the animation is a little strange, but in the simulator it works ok.

Boga
  • 371
  • 3
  • 14
0

It does not work the first time because the SwiftUI view must be created before executing the animation. It means that every animated view cannot be created like that:

if conditions
   show view

Instead, your code should look like this:

 ZStack(alignment: .bottom){
        VStack{
            Button("TAP HERE") {
                withAnimation(.spring()) {
                    showView.toggle()
                }
            }
            Spacer()
        }
        RoundedRectangle(cornerRadius: 30)
            .frame(height: UIScreen.main.bounds.height * 0.5)
            .transition(.move(edge: .bottom))
            .offset(y: showView ? 0 : UIScreen.main.bounds.height * 0.5)
    }
Arek
  • 375
  • 5
  • 5