Someone showed me the code below, when I was trying to figure out how to detect which views were being intercepted by one continuous DragGesture.
It works, but I would like to find a tutorial whre I can learn what's going on here.
From what I can tell, the background modifier is a closure, that calls a function which has a GeometryReader which returns a view.
I've Googled .background as a closure in swiftui and still can't find any form of tutorial that discuss what is going on here. Not looking for the answers, looking to learn.
Thank you
struct ContentView: View {
@State private var dragLocation = CGPoint.zero
@State private var dragInfo = " "
private func dragDetector(for name: String) -> some View {
GeometryReader { proxy in
let frame = proxy.frame(in: .global)
let isDragLocationInsideFrame = frame.contains(dragLocation)
let isDragLocationInsideCircle = isDragLocationInsideFrame &&
Circle().path(in: frame).contains(dragLocation)
Color.clear
.onChange(of: isDragLocationInsideCircle) { oldVal, newVal in
if dragLocation != .zero {
dragInfo = "\(newVal ? "entering" : "leaving") \(name)..."
}
}
}
}
var body: some View {
ZStack {
Color(white: 0.2)
VStack(spacing: 50) {
Text(dragInfo)
.foregroundStyle(.white)
HStack {
Circle()
.fill(.red)
.frame(width: 100, height: 100)
.background { dragDetector(for: "red") }
Circle()
.fill(.white)
.frame(width: 100, height: 100)
.background { dragDetector(for: "white") }
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.background { dragDetector(for: "blue") }
}
}
}
.gesture(
DragGesture(coordinateSpace: .global)
.onChanged { val in
dragLocation = val.location
}
.onEnded { val in
dragLocation = .zero
dragInfo = " "
}
)
}
}