0
0

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の@Stateと@Bindingの違いを解説してみました!

Posted at

SwiftUIを学び始めると、必ず出てくるのが@State@Binding
なんとなく使っているけどよく違いが分からないいう方も多いと思います。
この記事では、@State@Binding2つの違いとデータの流れを分かりやすく解説したいと思います!

@Stateとは?

  • 役割:そのViewが持つデータの保存場所

  • Viewの中で完結する状態を管理するときに使う。

ポイント: @StateはそのView自身の持ち物というイメージです

struct CounterView: View {
    @State  var count = 0
    
    var body: some View {
        VStack {
            Text("カウント: \(count)")
            Button("+1") {
                count += 1
            }
        }
    }
}
  • countはCounterViewだけが管理している

@Bindingとは?

  • 役割:親Viewから渡されたデータを参照する

  • データを所有せず、外部の状態を借りて使うイメージで、子Viewが親の状態を変更できます!

struct ChildrenView: View {
    @Binding var count: Int
    
    var body: some View {
        Stepper("Count: \(count)", value: $count)
    }
}

@State@Bindingの関係を図解

(イメージ)

親View: @State -----------------> 子View: @Binding
(データを所有)                 (データを参照)

ポイント

  • 親Viewがデータのオーナー

  • 子Viewはそのデータを借りて編集できる

実際の使用例

struct ContentView: View {
    @State private var count = 0
    
    var body: some View {
        VStack {
            Text("親で管理: \(count)")
            ChildrenView(count: $count)  // Bindingを渡す
        }
    }
}

struct ChildrenView: View {
    @Binding var count: Int
    
    var body: some View {
        Stepper("子で操作: \(count)", value: $count)
    }
}
  • 子Viewから操作しても、ContentViewの状態が更新される。

まとめ

@State = Viewが持つデータ

@Binding = 他のViewから借りるデータ

データの流れは親 → 子に流れるイメージ

状態管理の基本を押さえると、SwiftUIの理解が一気に深まるると思います!

以上、@State@Bindingの違いでした!ぜひ参考にしてみてください!🙌

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?