0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】GeometryReaderを使うとレイアウトが変わってしまう件

Last updated at Posted at 2022-08-07

22/8/8追記

こちらのページにGeometryReaderについて改めて整理しました

問題

動的にviewを作って各オブジェクトの位置を取得して、指定のY座標まで進んだら処理実行したい、なんてことありますよね。そんな時にGeometryReader使ったらレイアウト崩れちゃったんですけど!?ってお話。

  1. これがGeometryReaderなし
    image.png

  2. これがGeometryReaderあり
    image.png
    コンソールへのprint結果を見ると位置は取得できてそう。だけどレイアウト変わっちゃうと困ります・・・
    image.png

上記1,2の違いは、下記コードそのままが1, コメントアウトを解除したのが2

import SwiftUI
struct ContentView: View {
    var body: some View {
        VStack{
            ScrollView(.vertical, showsIndicators: false){
                VStack(spacing:0){
                    ForEach(1..<100) { num in
                        //GeometryReader {geometry in
                            Text("\(num)行目").background(Color.blue.opacity(0.1))
                        //    let _ = print(num, geometry.frame(in:.global).minY)
                        //}
                    }
                }
            }
        }
    }
}

解決

空のテキストを入れて、GeometryReaderのサイズをゼロにしてやりました

import SwiftUI
struct ContentView: View {
    var body: some View {
        VStack{
            ScrollView(.vertical, showsIndicators: false){
                VStack(spacing:0){
                    ForEach(1..<100) { num in
                        GeometryReader {geometry in
                            Text("")
                            let _ = print(num, geometry.frame(in:.global).minY)
                        }.frame(height:0)
                        Text("\(num)行目").background(Color.blue.opacity(0.1))
                    }
                }
            }
        }
    }
}

image.png
これで余計な余白はなくなって、コンソールで場所を取得できていることも確認できます(オブジェクトのサイズは取れてなくてスタート地点ですが)。

おしまい

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?