SwiftUI_visionOS_Note

Tap gesture

Mar 15, 2024
1 min read|

The .onTapGesture modifier functions much like a button and can even be customized to recognize multiple taps instead of just one (double-tap, triple-tap, etc.).

Create a button to change the colour of rectangle.

struct ContentView: View {
    
    @State var isSelected: Bool = false
    
var body: some View {
    VStack (spacing: 40){
        RoundedRectangle(cornerRadius: 25.0)
            .frame(height: 200)
            .padding(.horizontal)
            .foregroundStyle(isSelected ? Color.red : Color.blue)
        
        Button(action: {
            isSelected.toggle()
        }, label: {
            Text("Button")
                .padding()
                .padding(.horizontal, 20)
                .background(
                Capsule()
                    .stroke())
                
        })
        .buttonStyle(.plain)
    }
        
    }
}
swift

onTap Gesture works differently than the button.

  • We can put onTap gesture on any texts, shapes, images and anything.
  • Button shows the highlighted state, but tap gesture doesn’t
        
        Text("Tap Gesture")
            .padding()
            .padding(.horizontal, 20)
            .background(
            Capsule()
                .stroke())
            .onTapGesture {
                isSelected.toggle()
            }
swift

onTapGesture with Count and perform completion

count: number of taps to perform the action

just like instagram.

            .onTapGesture(count: 2, perform: {
                isSelected.toggle()
            })
swift

Subscribe to our newsletter

Get the latest news and updates from our team