skip to Main Content
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


  1. 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:

    Text("Click me to print my rect")
        .allowsHitTesting(false)
    

    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.

    Login or Signup to reply.
  2. 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

    Text("Click me to print my rect")
        .background(
            GeometryReader { geo in
                Color.red
                    .frame(maxWidth: .infinity, maxHeight: .infinity) // Add this line
                    .onTapGesture {
                        print(geo.frame(in: .global))
                    }
            }
        )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search