How to detect taps on a List cell row in SwiftUI?

Viewed 1106

Given a basic List with Text, how can i make the whole "cell" from left side of the screen to right, tappable in a List, not just the "Hello world" text?

    List {
         VStack {
             Text("Hello world")
         }    
         .contentShape(Rectangle())
         .onTapGesture {
            print("Tapped cell")  // This only triggers when you directly tap the Text
         }
     }
2 Answers

Add a Button and entire cell is tappable now:

VStack {
    Button(action: {
        
        print("Tapped")
    }) {
        Text("Hello world")
    }
}

Actually, all you really need to do is make sure the entire cell is filled with content. Changing the VStack to an HStack and adding a Spacer() will give you what you want.

    List {
         HStack {
             Text("Hello world")
             Spacer()
         }
         .contentShape(Rectangle())
         .onTapGesture {
            print("Tapped cell")  // This triggers when you tap anywhere in the cell
         }
     }
Related