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?

SwiftUIにおける @Environment(\.displayScale) の更新タイミング

Last updated at Posted at 2025-03-27

EnvironmentObject が便利なので、App全体で使うような変数を environmentObject として App でセットしてどこからでも参照できるようにしようとしてみたが、これは期待通り動かない。端末問わず常に displayScale = 1.0 となってしまう。

@main
struct SampleApp: App {
    @Environment(\.displayScale) var displayScale

    var body: some Scene {
        WindowGroup {
            RootScreen()
                .environmentObject(
                    AppEnv(
                        displayScale: displayScale // NG: 常に 1.0
                    )
                )
                .onAppeer {
                    print(displayScale)  // NG: 常に 1.0
                }
        }
    }

正しくは、各Viewで都度 displayScale を定義して body の中で参照してやる必要がある。

struct TopView: View {
    @Environment(\.displayScale) var displayScale

    var body: some View {
        MainView()
            .onAppeer {
                print(displayScale)  // 👌 iPhone16なら "3.0" 
            }
    }
}

それにしても久しぶりにQiita書いたな
最近はZennとか個人ブログに書くのが流行ってるのかな

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?