防止触摸从Hstack spacing传递到其他视图



我使用ZStackMapView之上显示HStack。我面临的问题是用户触摸仍然可以从Hstack之间的间距响应MapView。我该如何预防呢?我可以使用的一个技巧是设置不可见的背景色。

.background(Color.black.opacity(0.0001))
import SwiftUI
import MapKit
struct ConfusedView: View {
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 51.23,
longitude: -0.1275),
span: MKCoordinateSpan(
latitudeDelta: 0.5,
longitudeDelta: 0.5)
)
var body: some View {
ZStack {
Map(coordinateRegion: $region)
HStack(spacing: 50) {
Rectangle()
.fill(.red)
.frame(width: 100)
Rectangle()
.fill(.red)
.frame(width: 100)
Rectangle()
.fill(.red)
.frame(width: 100)
}
//.background(Color.black.opacity(0.0001))
.border(Color.green, width: 10)
.frame(height: 300)
}
}
}
struct ConfusedView_Previews: PreviewProvider {
static var previews: some View {
ConfusedView()
}
}

我也尝试使用contentShape,但没有工作。处理这个案子最好的办法是什么?

形象

我们有两种方法可以解决这个问题:

应该使用
  1. Color.black.opacity(0.0001)(即使在每通道10位的显示器上)。这产生了一种透明的颜色,它不会影响你的外观,以及一个可点击的区域,填补了它的框架。我不确定SwiftUI是否足够聪明,可以跳过渲染颜色,所以我不确定它是否会影响性能。

  2. 使用GeometryReader获取帧大小,然后使用contentShape:

    生成可点击区域
GeometryReader { proxy in
Color.clear.contentShape(Path(CGRect(origin: .zero, size: proxy.size)))
}

最新更新