LoginSignup
1
2

More than 1 year has passed since last update.

【SwiftUI】GeometryReaderを使うと座標がずれる

Last updated at Posted at 2021-11-29

現象

環境はXCode13.1。

座標や縦・横幅の取得に便利なGeometryReaderを使った時に、階層下のVStack内で生成したUI部品の座標がずれたので解決策をメモ。
HStackZStackでは未検証。

以下のようなコードを書いていた。(サイズなどは適当)

GeometryReader { geometry in
    VStack() {
        Button(action: {}){
            Text("Button")
                .foregroundColor(Color.white)
                .padding(.all, 10.0)
                .background(Color.blue)
        }
    }
}

おや...?
scleenshot-1
明らかに中央から表示がずれている...?

原因

VStackに色をつけてみるとこんな感じになる。
scleenshot-2
見やすさのためにheightを指定してやるとこんな感じ。
scleenshot-3

なぜかWidthが画面幅より狭くなっている...

解決策

と、いうことでVStackを画面いっぱいまで広げてやればいいので、以下のようにコードを変更。

GeometryReader { geometry in
    VStack() {
        Button(action: {}){
            Text("Button")
                .foregroundColor(Color.white)
                .padding(.all, 10.0)
                .background(Color.blue)
        }
        .frame(width: geometry.frame(in:.local).width, height: /*適当に*/)
        .background(Color.red)
    }
}

scleenshot-3
無事解決した。

geometry自体の横幅は画面サイズいっぱいまで広がっているので、原因をなかなか特定できなかった。
これは仕様なのかバグなのか...

1
2
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
1
2