import SwiftUI
struct TestGEO: View {
var body: some View {
VStack {
Text("Click me to print my rect")
// .padding(5) // Add padding, the `onTapGesture` is triggled
.background(
GeometryReader { geo in
Color.red
.onTapGesture {
print(geo.frame(in: .global))
}
}
)
}
}
}
#Preview {
TestGEO()
}
If comment the padding
line, the tapGesture can’t be trigged, but add padding make sense, so why?
2
Answers
I think the
Text
is blocking the tap gestures and stopping them from reaching the background. You can fix this by applying.allowsHitTesting(false)
, like this:However, what is not completely clear to me is why it worked when padding was applied. But since a tap can presumably go through the padding, maybe SwiftUI lets it go through the main content in this case too (or at least, through the holes in the text). If you apply
.contentShape(Rectangle())
after the padding then it doesn’t work with padding either.it only occupies the space of the actual text content, not the entire rectangle that you might expect. When you add a background to the Text view, the background only covers the area occupied by the text. By adding padding, you’re expanding the size of the Text view.
if you wish not to add padding you can add a GeometryReader frame