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 3 years have passed since last update.

[SwiftUI]Property Wrappers変数の変更イベント

Last updated at Posted at 2021-08-01

プロパティラッパー変数の@Stateなどの値はSwiftのビューに対して変更をデータバインドすることができますが、データバインド領域ではなく、変数が変更されたときに何かしらの処理を実行させる場合には、例えば、onAppearなどで状態変数が変更された後の処理を書いても、変更されたタイミングでコールされません。

ではどうするか、、、
onChangeメソッドを使い状態変数の値を監視することができます。

struct ContentView: View {

    @State var name: String
    
    var body: some View {
        
        VStack {
            // do something
        }
        .onChange(of: self.name, perform: { value in
            if let receivedUpdate = value {
              // 変更されたときに実行される
            }
        })
        
    }
    
}

はい、このようにすることで実行できます。
SwiftUIは慣れないと最初ここらへんでつまずくのでメモとして残しておきます。

状態管理の根本がわからない人でもっと理解を深めたい人はついでにReduxなどを勉強するとためになります。
多くのフレームワークが採用しているので今後の必須知識でしょう

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?