Tap Gesture in SwiftUI

DevTechie Inc
Jun 17, 2022


Photo by Timothy Muza on Unsplash

Tap gesture is used for brief taps on the screen to implement button-like interactions with your content.

Tap gestures detect one or more fingers touching the screen briefly. The fingers involved in these gestures must not move significantly from the initial touch points, and you can configure the number of times the fingers must touch the screen. For example, you might configure tap gesture recognizers to detect single taps, double taps, or triple taps.

Tap gestures are applied directly on views with the modifier called Gesture and adding struct called TapGesture.

struct TapGestureExample: View {
    @State private var showName = false    var body: some View {
        RoundedRectangle(cornerRadius: 20)
            .fill(LinearGradient(colors: [.purple, .blue], startPoint: .topLeading, endPoint: .bottomTrailing))
            .frame(maxHeight: 200)
            .overlay(Text("DevTechie").font(.largeTitle).opacity(showName ? 1 : 0))
            .gesture(TapGesture().onEnded({ _ in
                withAnimation { 
                    showName.toggle()
                }
            }))
    }
}
Another overload for TapGesture takes count of tap as a parameter so instead of single tap, we can have user tap 3 times before we show the title “DevTechie” as shown below:

struct TapGestureExample: View {
    @State private var showName = false
    var body: some View {
        RoundedRectangle(cornerRadius: 20)
            .fill(LinearGradient(colors: [.purple, .blue], startPoint: .topLeading, endPoint: .bottomTrailing))
            .frame(maxHeight: 200)
            .overlay(Text("DevTechie").font(.largeTitle).opacity(showName ? 1 : 0))
            .gesture(TapGesture(count: 3).onEnded({ _ in
                withAnimation { 
                    showName.toggle()
                }
            }))
    }
}
With that we have reached the end of this article. Thank you once again for reading. Don’t forget subscribe our weekly newsletter at https://www.devtechie.com