Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SwiftUIにおけるPreferenceの基礎概念

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 SwiftUIにおけるPreferenceの基礎概念

Avatar for Kota Minato

Kota Minato

May 21, 2025
Tweet

More Decks by Kota Minato

Other Decks in Technology

Transcript

  1. © 2025 Wantedly, Inc. 話すこと 01 Preferenceとはなにか ? 02 Binding

    vs Environment vs Preference 03 Wantedlyでの活用事例
  2. © 2025 Wantedly, Inc. 話すこと 01 Preferenceとはなにか ? 02 Binding

    vs Environment vs Preference 03 Wantedlyでの活用事例
  3. © 2025 Wantedly, Inc. 話すこと 01 Preferenceとはなにか ? 02 Binding

    vs Environment vs Preference 03 Wantedlyでの活用事例
  4. © 2025 Wantedly, Inc. Binding vs Environment vs Preference Binding、Environment、Preferenceを比較してみる

    @Environmentは上位View→下位Viewへの一方向の値注入 (広い範囲で共通の値を共有 ) @Bindingは親View→子Viewへの双方向の値注入 (データの保有者は親 View) Preferenceは子View→親Viewへの一方向の値注入 データの矢印の向きが異なります!
  5. © 2025 Wantedly, Inc. 話すこと 01 Preferenceとはなにか ? 02 Binding

    vs Environment vs Preference 03 Wantedlyでの活用事例
  6. © 2025 Wantedly, Inc. どうやって実装するのか PreferencesKeyに準拠したstructを作成 • PreferencesKeyに準拠するために必要なのはdefaultValue とreduce。 •

    defaultValue = 何も入れなかったときの値 • reduce = 子Viewが入れた値を親Viewが受け取るときの変 換処理を書く 今回はOffSetを常に更新して取得したかったので Valueに対してnextValueを加算していま す。
  7. © 2025 Wantedly, Inc. どうやって実装するのか • .preference(key: ScrollOffset.self, value: 値

    ) 子Viewから親Viewへ値を流す ※ 画面に影響を与えないようにColor.Clearを使用して値を取得します