@ObservedObject and Friends in SwiftUI
In this tutorial, we will know about @ObservedObject and friends in SwiftUI.
In SwiftUI, the @ObservedObject
is a property wrapper for observing changes to objects according to the ObservableObject
protocol. This wrapper allows SwiftUI to detect changes in the observed object and update the UI accordingly.
@ObservedObject
If we want something in our SwiftUI app to automatically update the interface whenever it changes, we can use the @ObservedObject
property wrapper.
Now, have a look at the example below.
import SwiftUI // A special container that keeps track of data. class DataManager: ObservableObject { // The score property that can be observed for changes. @Published var score: Int = 0 } struct ContentView: View { // Creating an instance of our DataManager to observe its changes @ObservedObject var dataManager = DataManager() var body: some View { // Arranges the UI elements vertically with spacing. VStack(spacing: 20) { // Displays the current score from DataManager. Text("Score: \(dataManager.score)") // Button to increase the score in DataManager. Button("Increase Score") { // Increases the score by 1. dataManager.score += 1 } } .font(.title2) } }
In the above program, I have created a class called DataManager
that will hold data and follow the ObservableObject
rules. There is a number called score
within this class that can change.
Inside the ContentView
, I have created an instance of DataManager
using @ObservedObject
. This means any changes in score will update the view.
I have used the Text
view to display the current score fetched from dataManager.score
.
Then, I have used a Button
to increase the score when we tap the button by modifying dataManager.score
.
Output:
Friends
Other than @ObservedObject
, there are a few more property wrappers to handle information in SwiftUI. Below are examples of some property wrappers.
- @State: Manage simple changes within one view.
- @Binding: Connects data between a parent and a child view.
- @EnvironmentObject: Shares data across multiple views.
- ObservableObject: Makes classes/structs observable for SwiftUI.
- @StateObject: Introduced in SwiftUI 2.0, it is similar to
@ObservedObject
, manages the lifecycle of an observed object tied to a view.
These property wrappers are vital for managing data flow and updates within SwiftUI views.
Leave a Reply