Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SwiftUI how can I animate a button offset when displayed

Tags:

swiftui

In SwiftUI, I want a button to appear from off screen by dropping in from the top into a final position when the view is initially displayed, I'm not asking for animation when the button is pressed.

I have tried:

Button(action: {}) {
    Text("Button")
}.offset(x: 0.0, y: 100.0).animation(.basic(duration: 5))

but no joy.

like image 359
J. Edgell Avatar asked Jun 21 '19 17:06

J. Edgell


2 Answers

If you would like to play with offset, this can get you started.

struct ContentView : View {
    @State private var offset: Length = 0

    var body: some View {
        Button(action: {}) { Text("Button") }
            .offset(x: 0.0, y: offset)
            .onAppear {
                withAnimation(.basic(duration: 5)) { self.offset = 100.0 }
            }
    }
}

I first suggested a .transition(.move(.top)), but I am updating my answer. Unless your button is on the border of the screen, it may not be a good fit. The move is limited to the size of the moved view. So you may need to use offset after all!

Note that to make it start way out of the screen, the initial value of offset can be negative.

like image 176
kontiki Avatar answered Sep 28 '22 14:09

kontiki


Presents a message box on top with animation:

import SwiftUI

struct MessageView: View {
    @State private var offset: CGFloat = -200.0
    var body: some View {
        VStack {
            HStack(alignment: .center) {
                Spacer()
                Text("Some message")
                    .foregroundColor(Color.white)
                    .font(Font.system(.headline).bold())
                Spacer()
            }.frame(height: 100)
                .background(Color.gray.opacity(0.3))
                .offset(x: 0.0, y: self.offset)
                .onAppear {
                    withAnimation(.easeOut(duration: 1.5)) { self.offset = 000.0
                    }
            }
            Spacer()
        }
    }
}
like image 21
Javier Calatrava Llavería Avatar answered Sep 28 '22 15:09

Javier Calatrava Llavería