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.