ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • differences between @Binding and @ObservedObject
    Swift/SwiftUI 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.

    'Swift > SwiftUI' 카테고리의 다른 글

    Zstack에서 버튼이 중첩해서 눌리는 현상(position vs offset)  (0) 2023.10.01
    Property Wrapper  (0) 2023.09.28
    sheet (Q)  (0) 2023.08.02
    swiftUI 뷰 - ViewModifier  (0) 2023.07.24
    swiftUI의 특징 (선언적 구문, 데이터 주도)  (0) 2023.07.24
Designed by Tistory.