Clicking in SwiftUI - how to get size of ZStack


Gerriet M. Denkmann
 

I have (macOS 12.3.1):

struct ContentView: View
{
var body: some View
{
GeometryReader
{ metrics in

VStack
{
... some HStacks ...

ZStack // Curves
{
... several Shapes with Path
}
.frame( maxHeight: metrics.size.height * 0.2 )
.onTapGesture()
{
NSLog("\(#function) Curves clicked")
}

...more stuff ...
}
}
}
}

Problem: clicking exactly on some Curve did work, but clicking anywhere else in my ZStack did not.

So I added as first item in my ZStack:
BackgroundRect()
.fill(.blue)
.opacity(0.01) // must be > 0

struct BackgroundRect: Shape
{
func path(in rect: CGRect) -> Path { Path(rect) }
}

Seems a bit clumsy, but this was the best I could find.

Now clicking does work. But I have no idea, where in my ZStack the click did occur.

So I replaced onTapGesture with:

.gesture ( DragGesture(minimumDistance: 0)
.onEnded
{ value in
print("Curves clicked at: \(value.location)")
}
)

But I am not interested in the absolut location of the click, but on its position relative to the bounds of my ZStack.

How do I get the bounds or frame or size of my ZStack?


Gerriet.