LoginSignup
11
7

More than 3 years have passed since last update.

SwiftUI Viewの動的サイズを取得するには(メモ)

Last updated at Posted at 2019-12-25

SwiftUIの動的に計算されているViewサイズの確認

やりたいこと

デバッグ時など、以下のように領域いっぱいにサイズ指定をした場合に、どういう値になっているのかを取得するメモです。

        Text("Hello")
            .frame(height:60)
            .frame(minWidth: 0, maxWidth: .infinity)
            .background(Color.red)
image.png

GeometryReaderをView要素のbackgroundに使う

ポイントは戻り値に空のTextなど描画対象となるViewを指定することのようで、EmptyViewなどではだめでした。

            .background(GeometryReader{ geometry -> Text in
                print("******", geometry.size)
                return Text("")
            })

実装例

        Text("Hello")
            .frame(height:60)
            .frame(minWidth: 0, maxWidth: .infinity)
            .background(Color.red)
            //追加
            .background(GeometryReader{ geometry -> Text in
                print("******", geometry.size)
                return Text("")
            })
実行結果
****** (375.0, 60.0)  //Portraitモード
****** (724.0, 60.0)  //Landscapeモード

Viewのframe全体を確認

GeometryReaderを用いてViewのframeを取得する場合には、.globalと.localで値を取ることができます。(UIViewのframeとboundsの違いのようで、親からの相対位置を取るなら.global)

            .background(GeometryReader{ geometry -> Text in
                // size → frame
                print("******",geometry.frame(in: .global))
                return Text("")
            })
実行結果
****** (0.0, 381.0, 375.0, 60.0)   //Portraitモード
****** (44.0, 147.0, 724.0, 60.0)  //Landscapeモード

SwiftUIはStoryboardを使っていた頃のAutolayout設定と比べて非常にシンプルに書けるのがありがたいですが、レイアウトが自動調整されたときにどういう値になっているのか想定と違う時があるので確認重要です。

11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7