swiftuiswiftui-ontapgestureswiftui-gridrow

Tap Gesture in GridRow doesn't work in empty spaces


I'm making a table with Grid like the one I'm showing in the screenshot.

(Picture link)

Everything is fine except the onTapGesture won't be trigger if the user taps in a place there is not text or there is not image. If the user taps in the image or in the text the tap gesture gets triggered.

Grid (alignment: .leading, horizontalSpacing: 0, verticalSpacing: 5) {
    GridRow {
        Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
        
        Text("Header 1")
            .gridColumnAlignment(.leading)
            .frame(width: 400, height: 60, alignment: .leading)

        Text("Header 2")
            .frame(width: 400, height: 60, alignment: .leading)

    }
    .background(Color.headerTableBackground)
    
    ForEach(personas, id: \.self) { persona in
        GridRow {
            Image(selection?.id == persona.id ? "RadioButtonOn" : "RadioButtonOff")
                .renderingMode(.original)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 30, height: 30)
                .gridCellUnsizedAxes(.horizontal)
                .frame(width: 40, alignment: .leading)
            Text(persona.name)
                .font(Font.helveticaNow(subtype: .Regular, size: 16))
                .gridColumnAlignment(.leading)
                .frame(width: 400, alignment: .leading)
                
            Text(persona.surname)
                .font(Font.helveticaNow(subtype: .Regular, size: 16))
                .frame(width: 400, alignment: .leading)
        }
        .onTapGesture {
            selection = persona
        }
        
        Divider().gridCellUnsizedAxes(.horizontal)
    }
}

Any idea where should I put the tap gesture?


Solution

  • Try adding .contentShape(Rectangle()) before the onTapGesture modifier:

    GridRow {
        // content
    }
    .contentShape(Rectangle()) // <- HERE
    .onTapGesture {
        selection = persona
    }