how can I make onTapGesture works only if user tap on circle not inside all frame of Circle in SwiftUI?

Viewed 372

I am using this down code for reading tap of user on Circle, the problem is here that it works on all part of frame 100X100 but I expect that it should work only on color filled Circle, how can I solve this issue?

    struct ContentView: View {
    

    var body: some View {

        
        Circle()
            .fill(Color.red)
            .frame(width: 100, height: 100, alignment: .center)
            .onTapGesture {
                print("tap")
            }
  
    }
}
1 Answers

A nice little hack would be to add a background layer to the circle (it can't be 100% clear or it wouldn't render, so I made it opacity 0.0001 which looks clear) and then add another tapGesture onto that layer. The new gesture will take priority in the background area and we can just leave it without an action so nothing happens.

Circle()
    .fill(Color.red)
    .frame(width: 100, height: 100, alignment: .center)
    .background(
        Color.black.opacity(0.0001).onTapGesture { }
    )
    .onTapGesture {
        print("tap")
    }
Related