← Back to archive

Development · SwiftUI

Handling taps with onTapGesture

Recognize single and repeated taps with onTapGesture and its count parameter.

Read the Korean original on Velog ↗English translation

Development archive cover

A view does not have to look like a button to respond to a tap. onTapGesture attaches an action directly to a view, with options for recognizing repeated taps.

onTapGesture

The supplied closure runs when SwiftUI recognizes the gesture. Unlike a standard button style, attaching a tap gesture does not automatically add a pressed-state highlight.

struct TapGestureStudy: View {
    
    @State var isSelected: Bool = false
    
    var body: some View {
        VStack(spacing: 40){
            RoundedRectangle(cornerRadius: 32)
                .foregroundColor(isSelected ? .green : .yellow)
                .frame(height: 200)
            // Default button
            Button {
                isSelected.toggle()
            } label: {
                Text("Button")
                    .foregroundColor(.white)
                    .frame(height: 50)
                    .frame(maxWidth: .infinity)
                    .background(Color.blue)
                    .cornerRadius(25)
            }
            // Text styled as a button
            Text("Tap Gesture")
                .foregroundColor(.white)
                .frame(height: 50)
                .frame(maxWidth: .infinity)
                .background(Color.blue)
                .cornerRadius(25)
                // Run when the tap is recognized
                .onTapGesture {
                    isSelected.toggle()
                }
        }
        .padding()
    }
}

Tap count

Set count to the number of consecutive taps required before the action runs.

struct TapGestureStudy: View {
    
    @State var isSelected: Bool = false
    
    var body: some View {
        VStack(spacing: 40){
            RoundedRectangle(cornerRadius: 32)
                .foregroundColor(isSelected ? .green : .yellow)
                .frame(height: 200)
            Text("Tap Gesture")
                .foregroundColor(.white)
                .frame(height: 50)
                .frame(maxWidth: .infinity)
                .background(Color.blue)
                .cornerRadius(25)
                // Run after three consecutive taps
                .onTapGesture(count: 3) {
                    isSelected.toggle()
                }
        }
        .padding()
    }
}
← Back to archive