Closed5

[SwigtUI] GeometryReader

🍤🍤

Viewサイズをいかに知るか。

  • SwiftUIのViewには、座標位置やサイズを示すプロパティがない
  • それらを知るための特別なViewがGeometryReader
  • GeometryReaderは特殊なView。
  • 自身のサイズと座標空間を返す関数をクロージャーとして保持している。
  • そのクロージャーを通して、自身のViewやRootViewのサイズ、座標位置を取得することができる。
  • Viewサイズや座標の計算が必要な場面で使っていくのが良い。
public struct GeometryReader<Content> : View where Content : View {

    public var content: (GeometryProxy) -> Content

    @inlinable public init(@ViewBuilder content: @escaping (GeometryProxy) -> Content)
🍤🍤

GeometryReader

GeometryReader
 GeometryReader { geometry in
            Text(String("geometry: \(geometry.size.debugDescription)"))
}

  • クロージャーの引数のgeometryはGeometryProxyプロトコルに準拠したインスタンス。
  • このインスタンスからViewのサイズや座標位置を取得できる。
  • 自身のViewサイズを知りたい時は、geometry.sizeにアクセスする。
🍤🍤

SafeAreaを取得したい時

  • 上記ViweサイズはSafeAreaが除外されている点に注意する。
SafeAreaを取得するコード
    var body: some View {
        GeometryReader { geometry in
            Text(String("\(geometry.safeAreaInsets)"))
        }
    }
}

  • 通常、セーフエリアにコンテンツを表示することはできない。
🍤🍤

入れ子になっているViewのサイズ取得

  • View全体ではなく、内側にあるViewのサイズを取りたい場合。
ImageとNavigationViewに挟まれた位置のViewサイズを取得する
  GeometryReader { geometry in
                                Text(String("\(geometry.size)"))
                            }

🍤🍤

xとyの取得

  • frameメソッドを使う事で、xとyも取得できる。
  • 引数はCoordinateSpaceというクラス
  • coordinateSpace: local:Viewの座標系 grobal:画面の座標系
  • セーフエリアも含まれるので注意すること
var body: some View {
        GeometryReader { geometry in
            Text(String("\(geometry.frame(in: .global))"))
        }
    }

  • CoordinateSpaceは自分でcoordinateSpaceメソッドを使って定義する事も可能
  • 下の例ではVStackでTestという名前のCoordinateSpaceを定義して、それに対する位置を取得している。
   GeometryReader { geometry in
                Text(String("\(geometry.frame(in: .named("Test")))"))
            }
このスクラップは2022/02/04にクローズされました