init(wrappedValue : () -> ObjectType )
Overview 概要
Create a state object in a View
, App
, or Scene
by applying the @State
attribute to a property declaration and providing an initial value that conforms to the Observable
protocol:
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 Observed
attribute. You can alternatively add the object to the environment of a view hierarchy by applying the environment
modifier:
ContentView()
.environmentObject(model)
If you create an environment object as shown in the code above, you can read the object inside Content
or any of its descendants using the Environment
attribute:
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 is
stored in the model:
Toggle("Enabled", isOn: $model.isEnabled)