メインコンテンツへスキップ
見出し画像

SwiftUIで子Viewのframeやsize, GeometryProxyを取得する

    概要

    基本的に細かいframeやサイズなどを親Viewが認知しなくてもサクサクUI構築できてしまうSwiftUIですが、複雑なアニメーションを再現したいときなど、時折子Viewのframeやサイズ情報が欲しくなることがあります。

    そんなニーズに便利なextensionをご紹介します!

    コード紹介

    実装

    extension View {
      func geometryReader(in coordinateSpace: CoordinateSpace, _ action: @escaping (CoordinateSpace, GeometryProxy) -> Void) -> some View {
        background {
          GeometryReader { geometryProxy in
            Color.clear.onChange(of: geometryProxy.frame(in: coordinateSpace), initial: true) { _ in
              action(coordinateSpace, geometryProxy)
            }
          }
        }
      }
    }

    ※このextension内で使用しているonChangeは以前の記事で別途紹介したextensionメソッドを使用しています。

    使用例

    struct SampleView: View {
      @State private var text = ""
      
      var body: some View {
        Text(text)
          .geometryReader(in: .global) { coordinateSpace, geometryProxy in
            text = """
            frame: \(geometryProxy.frame(in: coordinateSpace))
            
            size: \(geometryProxy.size)
            
            safeAreaInsets: \(geometryProxy.safeAreaInsets)
            """
          }
      }
    }
    
    #Preview {
      SampleView()
    }
    画像

    おわり

    お読みいただきありがとうございます!
    もしなにかのお役に立つことがございましたら、
    ♡を頂けますとすごく励みになります😊

    あなたへのおすすめ