What I encountered.

Recently when I’m testing Tap Gesture, but however I’ve got in some trouble. And touch event doesn’t work.

However, after find some answers on stackoverflow. I noticed that Color.clear’s contentShape is zero, which means it is untouchable.

And the solution is to add modifier .contentShape(Rectangle()) before .onTapGesture modifier.

Here’s my test code. You can comment or uncommnet the contentShape modifier to see what happened.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import SwiftUI

struct TapView: View {
@State var state = ""

var body: some View {
ZStack {
Color.yellow
.onTapGesture(count: 1, perform: {
self.state = "yellow"
})

ZStack {
Color.clear
// .contentShape(Rectangle())
.onTapGesture(count: 1, perform: {
print("www")
self.state = "clear"
})

.border(Color.black)

VStack {
Text("Title")
.onTapGesture(count: 1, perform: {
self.state = "Title"
})
Text(state)
.foregroundColor(.red)
}
.padding()
.border(/*@START_MENU_TOKEN@*/Color.black/*@END_MENU_TOKEN@*/)
// .contentShape(Rectangle())
.onTapGesture(count: /*@START_MENU_TOKEN@*/1/*@END_MENU_TOKEN@*/, perform: {
self.state = "Vstack"
})
}

}
.frame(width: 300, height: 300, alignment: .center)
}
}

struct TapView_Previews: PreviewProvider {
static var previews: some View {
TapView()
}
}

Something about ContentShape

In Hacking with Swift 100 days learning SwiftUI, it mentioned that when adding gestures to a Stack, it will allocate gestures to the Views in this Stack, but area that outside the Views, and inside the Stack is not. So, if we want to add some gestures to a Stack, we can use .contentShape() modifier.