2
4

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] iOS13でObservableObjectをインスタンス化する方法

Last updated at Posted at 2021-03-18

Problem

iOS14からは @StateObject が使えるので、Viewの中でObservableObjectをインスタンス化させることができます。

LibraryView.swift
struct LibraryView: View {
    @StateObject var book = Book()
    
    var body: some View {
        BookView(book: book)
    }
}

参考: Instantiate a Model Object in a View

ただ、iOS13では@StateObjectが使えないので、別の方法を考える必要があります。

Solution

Stackoverflowに解決策を書いている人がいました。
https://stackoverflow.com/a/62007843

親のView(LibraryView)で @State でObservableObjectをインスタンス化し、子View(LibraryViewImpl)に渡すようにすれば良さそうです。

LibraryView.swift
struct LibraryView: View {
    @State var book = Book()

    var body: some View {
        LibraryViewImpl(book: book)
    }
}

private struct LibraryViewImpl: View {
    @ObservedObject var book: Book

    var body: some View {
        BookView(book: book)
    }
}

参考

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?