简体   繁体   中英

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

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?

You can pass through touch events without use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM