How to create delayed tap animation in SwiftUI

In this tutorial, you will learn how to create a delayed tap animation in SwiftUI, where the animation only starts after a certain amount of time has passed after the user taps the view. This can be a useful technique to add some visual interest and feedback to your app's user interface.

We'll learn how to create a button that expands and contract after a delay. This is a fun effect that can be seen on a lot of buttons and cards.

Expand and contract a button using the tap gesture with delay

Dispatch Queue AsyncAfter  

You can use the DispatchQueue.main.asyncAfter to create a delay of 0.1 second.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
	tap = false
}

..

Button with States  

Let's start with a simple card with a show state and a tap gesture that toggles that state.

struct ContentView: View {
    @State var tap = false

    var body: some View {
        VStack {
            Text("View more").foregroundColor(.white)
        }
        .frame(width: 200, height: 200)
        .background(LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)), Color(#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1))]), startPoint: .topLeading, endPoint: .bottomTrailing))
        .mask(RoundedRectangle(cornerRadius: 30))
				.onTapGesture {
            tap.toggle()
        }
    }
}

..

Add a Scale Animation  

We'll add an animation that scales the card back and forth.

.scaleEffect(tap ? 1.2 : 1)
.animation(.spring(response: 0.4, dampingFraction: 0.6))

..

Reset Animation after Delay  

Instead of toggling between two animation states, we can use delay to reset the animation. This creates a fun interaction with the card.

.onTapGesture {
	tap = true
	DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
		tap = false
	}
}

..



Comments