🖼️ GeometryReader

用法:

GeometryReader { geometry in
    // geometry.size:size of the paraent
    // geometry.frame(in: .global):bounds of the parent
}
  • A GeometryReader is configured with a ViewBuilder (just like any other container view), but unlike other containers, the view builder for a geometry reader receives a parameter: the GeometryProxy.

  • The proxy has a property for the view’s proposed layout size and a subscript to resolve anchors.

  • GeometryReader reports its proposed size back as the actual size. Because of this sizing behavior, geometry readers are often especially useful when used as the background or overlay of another view: they become the exact size of the view. We can use this size either to draw something in the bounds of the view or to measure the size of the view. 👉 Thinking in SwiftUI, p.89, Ch.5, Custom Layout - GeometryReader

Example

import SwiftUI
import PlaygroundSupport

// live view
struct ContentView: View {
    var body: some View {
        HStack {
            
            Group {
                Text("Hello World").padding()
                    .background(Color.purple)
                MyRect()
                MyRect(.blue)
            } // Group
                // dashed line
                .overlay(Rectangle().stroke(Color.black, style: .init(dash: [6])))
                .padding(2)
            
        } // HStack (container)
            .frame(400, 100)
            .border(Color.yellow)
            .padding(200)
            .background(Color.gray)
            .shadow(radius: 8)
    }
}

PlaygroundPage.current.setLiveView(ContentView())

Last updated