So, that’s your position?

To date, all layout/design work done on SwiftUI has been fairly generic. SwiftUI makes laying things out pretty straight-forward if all you need is to throw elements onto the screen relatively neatly and not worry about precise locations.

Today we learned about GeometryReader. This is a View (like ScrollView), only it allows you to retrieve the size and to specific the position of your elements. Due to the different screen sizes of iOS devices, this isn’t necessarily what you want to be doing but, by returning size and location positions, you can reference these to align your elements where you want them.

Sounds complicated, and it does feel quite convoluted, which is presumably why the ease of not using GeometryReader is there for when precise location is not so important, but design alignment is.

GeometryReader { geo in
   Rectangle()
      .foregroundColor(.green)
      .onTapGesture {
         print("Width: \(geo.size.width), Height: \(geo.size.height)")
      }
   Rectangle()
      .foregroundColor(.red)
      .frame(width: geo.size.width*(2/3), height: geo.size.height/4)
      .position(x: geo.size.width/2, y: geo.size.height/2)
      .onTapGesture {
         print("Width: \(geo.size.width*(2/3)), Height: \(geo.size.height/4)")
      }
}