SwiftUI: Animate a Button View scale modifier up then back to its initial state

In the code snippet below the Button View when tapped will animate its scaleEffect up then return to its initial value.  DispatchQueue.main.asyncAfter is used to add a small delay after the first animation block. 

import SwiftUI

struct ContentView: View {

  @State private var scale: CGFloat = 1

  var body: some View {

    Button(action: {

      withAnimation(.easeIn(duration: 1)) {

        self.scale += 20

      }

      DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {

        withAnimation(.easeIn(duration: 1)) {

          self.scale = 1

        }

      }

    }) {

      Image(systemName: “sun.max.fill”)

        .font(.system(size: 40))

        .foregroundColor(Color.yellow)

        .scaleEffect(scale)

    }

  }

}

struct ContentView_Previews: PreviewProvider {

  static var previews: some View {

    ContentView()

  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s