GeometryReader with SwiftUI


Let's study GeometryReader when using SwiftUI

import SwiftUI


struct Home: View {

  var body: some View {


      

      HStack {

          Rectangle().fill(Color.yellow).frame(width: 30)

          

          VStack {

              Rectangle().fill(Color.blue).frame(height:200)

              

              GeometryReader {

                  self.contents(geometry: $0)

              }

              .background(Color.green)

              .border(Color.red, width: 4)

          }

          .coordinateSpace(name: "VStackCS")

          

      }

      .coordinateSpace(name: "HStackCS")

      

  }

    

    func contents(geometry g: GeometryProxy) -> some View {

        VStack {

            Text("Local").bold()    //1

            Text(stringFormat(for: g.frame(in: .local).origin))

                .padding(.bottom)

            

            Text("Global").bold()    //2

            Text(stringFormat(for: g.frame(in: .global).origin))

                .padding(.bottom)

            

            Text("Named VStackCS").bold()    //3

            Text(stringFormat(for: g.frame(in: .named("VStackCS")).origin))

            

            Text("Named HStackCS").bold()    //4

            Text(stringFormat(for: g.frame(in: .named("HStackCS")).origin))

        }

    }

    

    func stringFormat(for point: CGPoint) -> String {

        String(format: "(x: %.f, y: %.f)", arguments: [point.x, point.y])

    }

}

GeometryReader is container view which provides information of coordinate between parent view and child view.

enum CoordinateSpace {

    case global    //coordinate based on display

    case local    //coordinate based on geometry reader

    case named(AnyHashable)    //coordinate based on named view

}


Result screen:


1 => local means coordinate based on geometry reader(self), so the result is (0,0)

2 => global means coordinate based on display, so the result is (38, 252)

3 => naemd means coordinate based on named view

(0, 208) is the result from "VStack" and (38, 208) is the result from "HStack"