我正在 SwiftUI 上使用 ontapGesture 方法检查位置。顺便说一句,我对设置的矩形形状使用了 .onTapGesture 方法,当我打印位置时,即使单击矩形之外的精细区域,也可以将位置检查为打印。位置为负!如果我希望打印的值适合 200 * 200 的大小,我除了使用 if 语句之外别无选择吗?内容形状方法是否使可触摸区域比可见视图大一点?
struct TapGestureLocationExample: View {
var body: some View {
Rectangle()
.frame(width: 200, height: 200)
.background(Color.gray.opacity(0.3))
.onTapGesture { location in
print("Tapped at \(location)")
}
.clipShape(Rectangle())
.contentShape(Rectangle())
}
}
Tapped at (-8.666671752929688, 27.333328247070312)
Tapped at (-5.6666717529296875, -9.0)
Tapped at (9.0, -10.0)
我认为使用 ontapGesture 方法只能打印我想要的尺寸的位置信息。
默认情况下,有一个小填充,其中
gesture
甚至 Button
超出其范围。 IMO,这是关于 UI/UX 的,用于增加可点击区域。但是,有一些针对您的情况的解决方法:
~10
左右,因此您可以减少内容插入:Rectangle()
....
.onTapGesture { location in
print("Tapped at \(location)")
}
.contentShape(Rectangle().inset(by: 10))
tap location
:let rectangleSize: CGSize = .init(width: 200, height: 200)
Rectangle()
...
.simultaneousGesture(
SpatialTapGesture().onEnded { value in
guard (0...rectangleSize.width).contains(value.location.x) && (0...rectangleSize.height).contains(value.location.y) else {
return
}
print("Tapped at \(value.location)")
}
)