Apple Developer 에서 제공하는 SwiftUI 튜토리얼에서 GeoametryReader 에 대해서 다음과 같이 설명합니다.

<aside> 🧬 To provide relative size information of a parent view to its child views, you can use a GeometryReader. : 상위 뷰의 상대적 크기 정보를 하위 뷰에 제공하려면 GeometryReader 를 사용할 수 있습니다.

</aside>

왜 사용하나요?

저희가 VStack, HStack, ZStack 과 같은 View Builder 에 하위뷰들을 넣게되면 별도의 설정없이 화면에 자동으로 보여줍니다. 이것은 Parent View 상위뷰가 Child View 하위뷰에게 위치와 크기를 제안해주기 때문입니다.

그리고, 맘에 들지 않을 때 하위 뷰는 상위 뷰의 제안을 무시하고 선언할 수 있습니다.

이때 사용되는 것이 GeometryReader 입니다.

GeometryReader

Structure

A container view that defines its content as a function of its own size and coordinate space.

Overview

This view returns a flexible preferred size to its parent layout.

→ 상위뷰의 컨테이너의 크기를 통해서 하위뷰의 위치 및 크기를 선언하는데 사용!

코드 맛보기..!

스크린샷 2022-03-23 오후 7.41.50.png

// 클로저의 매개변수 네이밍으로 보통 proxy 혹은 geometry 를 사용하더라구요.
return GeometryReader { **proxy** in
            HStack(alignment: .bottom, spacing: **proxy.size.width** / 120) {
                ForEach(Array(data.enumerated()), id: \\.offset) { index, observation in
                    GraphCapsule(
                        index: index,
                        color: color,
                        height: **proxy.size.height**,
                        range: observation[keyPath: path],
                        overallRange: overallRange
                    )
                        .animation(.ripple(index: index))
                }
                .offset(x: 0, y: **proxy.size.height** * heightRatio)
            }
        }
// 출처: Landmark 튜토리얼 앱(HikeGraph)

GeometryReader 는 아래와 같은 이니셜라이저를 통해서 사용합니다. 그래서 클로저의 매개변수로 GeometryProxy 를 전달해주고 있어요.(그래서 네이밍도 그러한가 봅니다.)

init(content: @escaping (GeometryProxy) -> Content)