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】@Bindingの動きと使い方

Posted at

@Bindingはどのようなときに使うのか

@Stateで作成した変数の更新を別の画面で共有したいときに利用されるのが、SwiftUIのデータバインディング機能の一つである@Bindingです。

@State@Bindingは密接に関連しており、それぞれがどのように作用するのか、そしてどのように使用するのかについて見ていきましょう!

@Bindingとは

@Bindingは、他のビューで管理されている状態を参照・更新するためのプロパティラッパーです。他のビューの状態を変更する際に使用され、状態の変更が自動的に反映されます。

これらのプロパティラッパーを使うことで、SwiftUIでは簡単に状態を管理し、ビュー間でデータの受け渡しや同期が行えます。

@Bindingの使用例

ContentView.swift
// 親View (ContentView)

import SwiftUI

struct ContentView: View {
    @State var isShowBView = false
    
    var body: some View {
        Button {
            isShowBView = true
        } label: {
            Text("BViewへ遷移")
                .font(.largeTitle)
        }
        .sheet(isPresented: $isShowBView) {
            BView(isShowBView: $isShowBView)
        }
    }
}

@StateでisShowBViewと言うBool型(trueかfalse)を宣言します。

ContentViewが表示されたときは、isShowBViewがfalseになっているので、
.sheet(isPresented: $isShowBView)内が実行されません。

BView.swift
// 子View (BView)

import SwiftUI

struct BView: View {
    @Binding var isShowBView: Bool
    
    var body: some View {
        ZStack {
                .edgesIgnoringSafeArea(.all)
            VStack {
                Text("BView")
                    .font(.largeTitle)
                Button {
                    isShowBView = false
                } label: {
                    Text("閉じる")
                    .font(.largeTitle)
                    .padding()
                }
            }
        }
    }
}

子View側で@Binding変数の準備をして、親View側から子Viewを呼び出します。

ContentViewから抜粋
BView(isShowBView: $isShowBView)

引数の頭に$(ドルマーク)を付けることで子Viewの@Bindingのプロパティと紐付けられます。

親Viewへの紐付けが完了した@Binding変数は、@State変数と同じくSwiftUIの監視対象になります。
これにより、子Viewと親Viewのどちらからでもプロパティの更新が可能になり、どちらかの更新を検知するとSwiftUIが子Viewと親ViewのViewを再描画します。

動きを見てみよう

「BViewへ遷移」ボタンを押すと、isShowBViewがtrueになり、isShowBViewが再描画され、.sheet(isPresented: $isShowBView)内が実行されてBViewに画面遷移します。

image.png

「閉じる」ボタンを押すと、isShowBViewがfalseになり、isShowBViewが再描画され、.sheet(isPresented: $isShowBView)内が実行されてContentViewに画面遷移します。

image.png

@Bindingのまとめ

@State@Bindingでデータ共有されるView間は親子関係である必要があります。

呼び出す側のViewを「親View 」、呼び出される側のViewを「子View」と呼んでいます。

上記のコードでは、

・親View  ⇨  呼び出す側「ContentView」
・子View  ⇨  呼び出される側「BView」

となります。

@Bindingというのは、View間でのデータの共有ができる修飾子です。
画面Aと画面Bがあるとすると、画面Bで画面Aの@Stateを変更したいときに@Bindingを使います。


@Stateについては下記の記事で解説しています

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?