Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to pass touches through a view to those below it?

Tags:

ios

swift

swiftui

I have a SwiftUI view that is displayed over other views, and have found that using Color.clear like this below seems to allow touch interactions to pass through to anything under it:

var body: some View {
    VStack {
        Spacer()
        HStack {
            Spacer()
            SomeCustomContent()
            Spacer()
        }
        .overlay(GeometryReader { proxy in
            Color.clear.preference(key: MyCustomHeightPreferenceKey.self, value: proxy.size.height)
        })
    }
}

Is this the correct way to make touches pass through to the views below, or it this just a coincidental quirk/bug in SwiftUI behaviour that Apple might fix/change as swiftui matures?

If not, what is the correct way to pass the touches through?

like image 675
Gsp Avatar asked Sep 12 '25 06:09

Gsp


1 Answers

You can pass through touch events without using a clear color like this:

var body: some View {
    Rectangle()
        .overlay(
            Circle()
                .fill(.blue)
                .allowsHitTesting(false) // <--- Passes through gestures
        )
}

Asperi mentioned this solution in a comment above, and you can also find a good blog about this topic here: https://www.hackingwithswift.com/books/ios-swiftui/disabling-user-interactivity-with-allowshittesting

like image 55
Scott Marchant Avatar answered Sep 14 '25 21:09

Scott Marchant