【问题标题】:Prevent touch passing from Hstack spacing to other viewsPrevent touch passing from Hstack spacing to other views
【发布时间】:2022-12-01 15:13:37
【问题描述】:

I am displaying HStack on top of MapView using ZStack. The problem that i am facing is user touches can still respond to MapView from the Spacing between Hstack. How can i prevent this? A trick that i can use is set invisible background color.

.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()
    }
}

I also tried using contentShape but didnot work. Whats the best way to handle this case?

Image

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    There are 2 ways we can solve this problem:

    1. Color.black.opacity(0.0001) should be used (even on 10-bits-per-channel displays). This produces a colour that is so transparent that it has no effect on your appearance, as well as a tappable area that fills its frame. I'm not sure if SwiftUI is smart enough to skip rendering the colour, so I'm not sure if it affects performance.

    2. Get the frame size with a GeometryReader, then generate the tappable area with a contentShape:

      GeometryReader { proxy in
          Color.clear.contentShape(Path(CGRect(origin: .zero, size: proxy.size)))
      }
      

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 2022-10-04
      • 2022-12-27
      • 2022-12-27
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多