Tap Gesture and List in SwiftUI

In this post, we’ll explore how to utilize tap gestures within a list. Our objective is:

Therefore, we have a list of options (or whatever you prefer) that we can enable or disable.

We will define an Option type:

struct Option: Identifiable {
    let id = UUID()
    var name: String
    var enabled: Bool
}

In the view, we declare a list that iterates over a list of options, retrieving both the index and the element for each iteration. For each individual element, we display the name. If the enable option is set to true, we also display an image of a checkmark. When the user taps on a row, the status of the property is toggled.

struct ContentView: View {
    @State var options = [Option(name: "Option1", enabled: false),
                   Option(name: "Option2", enabled: false),
                   Option(name: "Option3", enabled: false)]
    
    var body: some View {
        List(Array(options.enumerated()), id: \.offset) { index, option in
            HStack() {
                Text(option.name)
                Spacer()
                if option.enabled {
                    Image(systemName: "chevron.down")
                        .foregroundColor(.gray)
                }
            }.contentShape(Rectangle())
            .onTapGesture {
                options[index].enabled = !options[index].enabled
            }
        }
    }
}

Note that we add a contentShape to cover the entire width of the list, and it’s on this shape that the onTap gesture is applied. The options are declared as a @State because we need to change the ‘enabled’ value, and these changes must be propagated to the UI.

Note: English is not my native language, sorry for any errors. I use ChatGPT only to generate the banner of the post, the content is human.

share this post with friends

Picture of Nicola De filippo

Nicola De filippo

I'm a software engineer who adds to the passion for technologies the wisdom and the experience without losing the wonder for the world. I love to create new projects and to help people and teams to improve

Leave a comment

Your email address will not be published. Required fields are marked *

Who I am

I'm a software engineer who adds to the passion for technologies the wisdom and the experience without losing the wonder for the world. I love to create new projects and to help people and teams to improve.

Follow Me Here

Get The Latest Updates

Periodically receive my super contents on coding and programming

join the family;)

Recent Posts