SwiftUI tappable StackView

There is one problem I recently faced with onTapGesture with Stack Views. Unlike all views, Stack Views (HStack, VStack, ZStack) could not receive events at their space.
Let see the example below

struct ContentView: View {
    
    var body: some View {
        ForEach (Array(0...10), id: \.self) { index in
            HStack {
                Text("Row ~ \(index)")
                    .background(Color.green)
                    .padding()
                Spacer()
            }
            .frame(width: 300, height: 50, alignment: .center)
            .border(Color.gray)
            .padding(3)
            .onTapGesture {
                print("Tapped index \(index)")
            }
        }
    }
}

When I tap the gree area ( Row ~ i ) console will print out Tapped Index. But when I tap outside the green zone, even it's inside HStack's area, nothing will happen.

So how to resolve this issue?. One solution is specifying a rectangle shape as contentShape

HStack {
    Text("Row ~ \(index)")
        .background(Color.green)
        .padding()
    Spacer()
}
.frame(width: 300, height: 50, alignment: .center)
.contentShape(Rectangle())
.border(Color.gray)
.padding(3)
.onTapGesture {
    print("Tapped index \(index)")
}

Or we could add background for StackView

HStack {
    Text("Row ~ \(index)")
        .foregroundColor(.white)
        .padding(20)
    Spacer()
}
.frame(width: 300, height: 50, alignment: .center)

.background(Color.green)
.clipShape(Capsule())

.padding(1)
.onTapGesture {
    print("Tapped index \(index)")
}

I just add .clipShape to trim the background and make it nicer.

Now, we could tap anywhere inside StackView. That will help to resolve some problems from your own, please try and give me a thumbs up.

Happy coding.