Building a Simple Tap Gesture Element in SwiftUI

Md. Jamal Uddin
2 min readMay 11, 2024

--

Photo by Blake Wisz on Unsplash

Creating a simple tap gesture in SwiftUI is quite straightforward. Here’s a basic example of how you can add a tap gesture to a text element that changes its color upon being tapped:

//  GestureRecognizer.swift
// GestureRecognizer
// Created by Md. Jamal Uddin on 11/5/24.

import SwiftUI

struct GestureRecognizer: View {
@State private var flag = false

var body: some View {
VStack {
Text("Gesture Recognizer").font(.title)
Text("Tap Me")
.font(.largeTitle)
.foregroundColor(.white)
.padding(15)
.background(flag ? Color.green : Color.gray)
.onTapGesture {
flag.toggle()
}
}
}
}

#Preview {
GestureRecognizer()
}

Run the code on the iOS simulator that will look same as below:

Button color change on Tap

In this example, the @State property flag keeps track of whether the text has been tapped. The .onTapGesture modifier is used to change the state when the text is tapped, causing the view to re-render with the new color.

If you’re looking to handle multiple taps, such as a double tap, you can specify the count parameter within the .onTapGesture modifier:

.onTapGesture(count: 2) {
flag.toggle()
}

For more advanced gestures, you can use the gesturemodifier with gesture structs like DragGesture, LongPressGesture, MagnifyGesture, RotateGesture, and TapGesture. These provide onEnded and onChanged modifiers to take action when the gestures are completed or in flight, respectively.

Remember, SwiftUI makes it easy to combine gestures and create complex interactions, so feel free to experiment with different combinations to achieve the desired user experience in your app.

Happy coding! 🚀

--

--

Md. Jamal Uddin

Software engineer passionate about building and delivering SaaS apps using React Native. Agile enthusiast who occasionally writes blog posts about life and tech