0

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

user3069232
  • 8,587
  • 7
  • 46
  • 87
  • 1
    `GeometryReader` is usually used to figure out how much space you have to render views inside of it. `geo` doesn't change in `onTapGesture` because it's unrelated to the view. What you're looking for are `PreferenceKeys`, they're not super easy to use. – EmilioPelaez Jan 27 '22 at 20:04
  • 1
    Does this answer your question https://stackoverflow.com/a/67242214/12299030? Or this one https://stackoverflow.com/a/63223498/12299030? – Asperi Jan 27 '22 at 20:19
  • Yes, the answer is in encapsulating the geometryReader inside a background or overlay tag and then reporting the global position! THANKS – user3069232 Jan 27 '22 at 20:30

0 Answers0