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.

【Swift】親Viewから子Viewに自作クラスのインスタンスを渡す方法

Posted at

はじめに

備忘録
View間での「自作クラスのメンバ変数」の受け渡しでつまずいたので書き残します。
自作クラスのインスタンスごと子Viewに渡すことができます。
どなたかのお役に立てれば幸いです。

解決方法

クラスの定義は以下のようになっています。
ObservableObjectとして定義することで値の受け渡しができるようにしています。

class SampleClass: ObservableObject {
    @Published var str = "hoge"
            :  // 他の処理
}

Viewの定義は以下です。
まず親Viewでクラスのインスタンスを@ObservedObjectとして作成し、SubViewの引数としてインスタンスを渡します。
子Viewでも@ObservedObjectとして渡された変数を定義することでインスタンスを受け取ります。

struct ContentView: View {
    @ObservedObject var sampleClass = SampleClass()
    @State private var isPressed: Bool = false

    var body: some View {
        if isPressed {
            SubView(sampleClass: sampleClass)
        } else {
            Button {
                isPressed.toggle()
            } label: {
                Text("button")
            }
        }
    }
}

struct SubView: View {
    @ObservedObject var sampleClass: SampleClass
    
    var body: some View {
        Text(sampleClass.str)
    }
}

この方法では、インスタンスを初期化することなく複数のViewで共有できます。
そのため、例えばメンバ変数に更新があった時などに、最新の値を子Viewに反映させることができます。

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?