Structure

StateObject

A property wrapper type that instantiates an observable object. あるプロパティラッパー型、それはある監視可能オブジェクトをインスタンス化するものです。

Declaration 宣言

@frozen @propertyWrapper struct StateObject<ObjectType> where ObjectType : ObservableObject

Overview 概要

Create a state object in a View, App, or Scene by applying the @StateObject attribute to a property declaration and providing an initial value that conforms to the ObservableObject protocol:


@StateObject var model = DataModel()

SwiftUI creates a new instance of the object only once for each instance of the structure that declares the object. When published properties of the observable object change, SwiftUI updates the parts of any view that depend on those properties:


Text(model.title) // Updates the view any time `title` changes.

You can pass the state object into a property that has the ObservedObject attribute. You can alternatively add the object to the environment of a view hierarchy by applying the environmentObject(_:) modifier:


ContentView()
    .environmentObject(model)

If you create an environment object as shown in the code above, you can read the object inside ContentView or any of its descendants using the EnvironmentObject attribute:


@EnvironmentObject var model: DataModel

Get a Binding to one of the state object’s properties using the $ operator. Use a binding when you want to create a two-way connection to one of the object’s properties. For example, you can let a Toggle control a Boolean value called isEnabled stored in the model:


Toggle("Enabled", isOn: $model.isEnabled)

Topics 話題

Creating a State Object

Getting the Value 値を取得する

Default Implementations 省略時実装

Relationships 関係

Conforms To 次に準拠

See Also 参照

Model Data モデルデータ