Am new enough to SwiftUI that I that are still some concepts that confuse me. Case in point: .background
The code below is meant to detect when the user drags their finger over different areas, in this case three different size circles placed over each other.
The code works, but I get lost trying to figure out how the logic works.
.background calls a function that's a view builder, yet doesn't an actual view? Unless Color.clear is the view it's returning?
I have more questions, but might as well start with .background since it comes first? I think?
Thanks
import SwiftUI
struct ContentView: View {
@State private var dragLocation = CGPoint.zero
@State private var dragInfo = " "
@State private var secondText = "..."
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)
.padding(.top, 60)
.foregroundStyle(.white)
Text(secondText)
.foregroundStyle(.white)
Spacer()
ZStack {
Circle()
.fill(.red)
.frame(width: 200, height: 200)
.background { dragDetector(for: "red") }
Circle()
.fill(.white)
.frame(width: 120, height: 120)
.background { dragDetector(for: "white") }
Circle()
.fill(.blue)
.frame(width: 50, height: 50)
.background { dragDetector(for: "blue") }
}
.padding(.bottom, 30)
}
}
.ignoresSafeArea()
.gesture(
DragGesture(coordinateSpace: .global)
.onChanged { val in
dragLocation = val.location
secondText = "\(Int(dragLocation.x)) ... \(Int(dragLocation.y))"
}
.onEnded { val in
dragLocation = .zero
dragInfo = " "
}
)
}
}
#Preview {
ContentView()
}