@ObservableObject / @Published
@ObservedObject
The use of is@State
very similar to , from the name it seems that it is used to modify an object, and this object canView
be used by multiple independent. If you use@ObservedObject
to modify an object, then that object must implementObservableObject
the protocol, and then use@Published
to modify the properties in the object, indicating that this property needs to beSwiftUI
monitored
@EnvironmentObject
@EnvironmentObject
Decorators are for the global environment. Through it, we can avoid creating at the initialView
timeObservableObject
, but get it from the environmentObservableObject
@EnvironmentObject
The way it works is thatEnvironment
it looks up the required instance of
@State
-
By using
@State
the decorator we can associateView
the state of the . The propertiesSwiftUI
that have been used with@State
the decorator stored in a special memory area, and this areaView struct
is isolated from the . When@State
the decorated property changes,SwiftUI
it will be based on the new property value recreates the view -
Create a variable with an initial value
@State private var isPlaying: Bool = false
@Binding
- Sometimes we will pass a view attribute to a child node, but it cannot be passed directly to the child node, because the value transmission form
Swift
in is the value type transmission method, that is, the one passed to the child node is a copied value. But after being modified by@Binding
the decorator , the attribute becomes a reference type, and the transfer becomes a reference transfer, so that the state of the parent-child view can be associated - When passing attributes, use
$
to pass
@Environment
- Through the
@Environment
modified attribute, we open a transformation that monitors system-level information. In this example, onceCalendar, Locale, ColorScheme
a transformation occurs, the definedCalendarView
will be refreshed
struct CalendarView: View {
@Environment(\.calendar) var calendar: Calendar
@Environment(\.locale) var locale: Locale
@Environment(\.colorScheme) var colorScheme: ColorScheme
var body: some View {
return Text(locale.identifier)
}
}