Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HStack: onTapGesture only works on elements

Tags:

swiftui

I have this example:

struct ContentView: View {
    
    var body: some View {
        HStack {

            Text("part1")

            Spacer()

            Text("part2")

            Spacer()

            Text("part3")

        }
        .onTapGesture {
            print("tapped")
        }
    }
    
}

The problem is, that the .onTapGesture is only getting called, when I tap on a Text, but not if I tap on the space between the elements.

I tried to but a Rectangle().fill(Color.clear) as a background to the HStack, but it didn't work either (it just works, if I put i. e. Color.blue).

like image 944
Lupurus Avatar asked Dec 18 '22 12:12

Lupurus


1 Answers

It needs to specify content shape to cover all area, because by default only opaque things handle gesture

}
.contentShape(Rectangle())      // << here !!
.onTapGesture {
    print("tapped")
}
like image 78
Asperi Avatar answered Jan 12 '23 10:01

Asperi