Swift/SwiftUI
differences between @Binding and @ObservedObject
Lyla.
2023. 8. 24. 00:34
In this example, we'll create a simple app with a counter. Tapping a button in the child view will increment the counter, and the updated counter value will be shown in both the parent and child views.
import SwiftUI
struct ContentView: View {
@State private var counter: Int = 0
var body: some View {
VStack {
Text("Counter in Parent: \(counter)")
ChildView(counter: $counter)
}
}
}
struct ChildView: View {
@Binding var counter: Int
var body: some View {
Button("Increment Counter") {
counter += 1
}
}
}
In this example, we'll use @ObservedObject to manage the state of a custom data model. The child view will display a person's name from the observed object, and a button will change the name.
import SwiftUI
class Person: ObservableObject {
@Published var name: String = "John"
}
struct ContentView: View {
@ObservedObject var person = Person()
var body: some View {
VStack {
Text("Person's Name: \(person.name)")
ChildView(person: person)
}
}
}
struct ChildView: View {
@ObservedObject var person: Person
var body: some View {
Button("Change Name") {
person.name = "Alice"
}
}
}
In this example, the Person class conforms to ObservableObject and uses @Published to automatically notify observers when the name property changes. The ContentView observes changes in the person object using @ObservedObject, and changes to the name made within ChildView are automatically reflected in both views.