简体   繁体   中英

SwiftUI - why does contentShape block clicking on an overlay?

This is some boiled down code from a real app. I tried to use an offset overlay to create a little popup that sits next to an item in a list. I discovered that contentShape() would interfere with tapGesture on the overlay. If I uncomment the .contentShape(Rectangle()) line in the following example, you can no longer click on the blue overlay.

Anyone understand why? Maybe it's a bug. I'm running this on macOS 11.2.3.

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            OverlayTapTest()
                // .contentShape(Rectangle())
                .zIndex(1)
            Text("Line 2")
            Text("Line 3")
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}


struct OverlayTapTest: View {
    var body: some View {
        Text("OverlayTapTest - Test")
            .contentShape(Rectangle())
            .onTapGesture { print("Tapped Text") }
            .overlay(
                Text("OverlayTapTest - Overlay")
                    .contentShape(Rectangle())
                    .onTapGesture { print("Tapped Overlay") }
                    .background(Color.blue)
                    .offset(x: 20, y: 18),
                alignment:.topLeading
            )
    }
}

You used onTapGesture in wrong order, see the working way:


struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            OverlayTapTest()
                 .contentShape(Rectangle())
                .zIndex(1)
            Text("Line 2")
            Text("Line 3")
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}


struct OverlayTapTest: View {
    
    var body: some View {
        
        Text("OverlayTapTest - Test")
            .contentShape(Rectangle())
            .overlay(Text("OverlayTapTest - Overlay")
                    .contentShape(Rectangle())
                    .onTapGesture { print("Tapped Overlay") }
                    .background(Color.blue)
                    .offset(x: 20, y: 18),
                alignment:.topLeading)
            .onTapGesture { print("Tapped Text") }   // <<: Here
            
    }
}

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