如果我将多个视图连续放置而没有空格(或者它们之间只有很小的空间),并附加一些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个被点击的按钮。有办法吗?
我花了几个小时解决这个问题,在我发布此问题后,我找到了解决方案。如此简单-只需添加contentShape
修饰符
...
.frame(width: 40, height: 50)
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0)
...