Swift 5.5 iOS 15
Trying to understand geometryReader in SwiftUI, but missed something critical. This app simply draws 4 dots in different places on the screen, but the geometry reader reports them as all being in the same place?
How do I get the coordinates of the dots so that I can reuse said coordinates to draw a lines between them?
import SwiftUI
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
struct ContentView: View {
var body: some View {
OuterView()
.background(.red)
}
}
struct OuterView: View {
var body: some View {
VStack {
Text("Top")
InnerView()
.background(.green)
Text("Bottom")
}.coordinateSpace(name: "Custom")
}
}
struct InnerView: View {
var body: some View {
GeometryReader { geo in
ForEach((0..<4), id:\.self) {_ in
Circle()
.fill(Color.red)
.frame(width: 64, height: 64)
.position(returnRandom())
.onTapGesture {
print("Custom : \(geo.frame(in: .named("Custom")).midX)")
print("Global center: \(geo.frame(in: .global).midX) x \(geo.frame(in: .global).midY)")
print("Local center: \(geo.frame(in: .local).midX) x \(geo.frame(in: .local).midY)")
}
}
}
}
func returnRandom() -> CGPoint {
let x = Double.random(in: 0..<width)
let y = Double.random(in: 0..<height)
return CGPoint(x: x, y: y)
}
}
All my dots report as being
Custom : 195.0
Global center: 195.0 x 430.60424804687494
Local center: 195.0 x 350.96183268229163
Custom : 195.0
Global center: 195.0 x 430.60424804687494
Local center: 195.0 x 350.96183268229163
Using onAppear doesn't report co-ordinates either