SwiftUI_property decorators


@ObservableObject / @Published

  • @ObservedObjectThe use of is @Statevery similar to , from the name it seems that it is used to modify an object, and this object can Viewbe used by multiple independent. If you use @ObservedObjectto modify an object, then that object must implement ObservableObjectthe protocol, and then use @Publishedto modify the properties in the object, indicating that this property needs to be SwiftUImonitored

@EnvironmentObject

  • @EnvironmentObjectDecorators are for the global environment. Through it, we can avoid creating at the initial Viewtime ObservableObject, but get it from the environmentObservableObject
  • @EnvironmentObjectThe way it works is that Environmentit looks up the required instance of

@State

  • By using @Statethe decorator we can associate Viewthe state of the . The properties SwiftUIthat have been used with @Statethe decorator stored in a special memory area, and this area View structis isolated from the . When @Statethe decorated property changes, SwiftUIit 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 Swiftin is the value type transmission method, that is, the one passed to the child node is a copied value. But after being modified by @Bindingthe 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 @Environmentmodified attribute, we open a transformation that monitors system-level information. In this example, once Calendar, Locale, ColorSchemea transformation occurs, the defined CalendarViewwill 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)
    }
}

Guess you like

Origin blog.csdn.net/FlyingKuiKui/article/details/129842394