SwuftUI手势位置检测到视图边框之外的点击

问题描述 投票:0回答:1

如果我将多个视图连续放置而没有空格(或者它们之间只有很小的空间),并附加一些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
                        }
                    )
                }
            }
        }
    }
}

和行为:

enter image description here

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

swiftui gesture
1个回答
0
投票

我花了几个小时解决这个问题,在我发布此问题后,我找到了解决方案。如此简单-只需添加contentShape修饰符

  ...
                       .frame(width: 40, height: 50)
                       .contentShape(Rectangle())
                    .gesture(DragGesture(minimumDistance: 0)
    ...
© www.soinside.com 2019 - 2024. All rights reserved.