SwiftUI 手势位置检测点击视图边界

SwuftUI Gesture location detect clicks out of View border

如果我将多个视图排成一行,没有 space(或者它们之间的 space 很少),并附加一些 Gesture 操作,我将无法正确检测, 哪一个被点击了。手势内部似乎有一些我无法删除的填充。

示例代码如下:

struct ContentView: View {
    @State var tap = 0
    @State var lastClick = CGPoint.zero
    var body: some View {
        VStack{
            Text("last tap: \(tap)")
            Text("coordinates: (x: \(Int(lastClick.x)), y: \(Int(lastClick.y)))")
            HStack(spacing: 0){
                ForEach(0...4, id: \.self){ind in
                    RoundedRectangle(cornerRadius: 10)
                        .foregroundColor(Color.gray)
                        .overlay(Text("\(ind)"))
                        .overlay(Circle()
                            .frame(width: 4, height: 4)
                            .foregroundColor(self.tap == ind ? Color.red : Color.clear)
                            .position(self.lastClick)

                        )
                        .frame(width: 40, height: 50)
                        //.border(Color.black, width: 0.5)
                    .gesture(DragGesture(minimumDistance: 0)
                        .onEnded(){value in
                            self.tap = ind
                            self.lastClick = value.startLocation
                        }
                    )
                }
            }
        }
    }
}

和行为:

我希望 Gesture 在点击位置变为负数时检测 0 个点击的按钮。有办法吗?

我花了几个小时解决这个问题,就在我 post 这个问题之后,我找到了解决方案。 非常简单 - 只需添加一个 contentShape 修饰符

  ...
                       .frame(width: 40, height: 50)
                       .contentShape(Rectangle())
                    .gesture(DragGesture(minimumDistance: 0)
    ...