简体   繁体   中英

How to update ParentView after updating SubView @ObservedObject SwiftUI

This is a simple example for my case. I have a @ObservedObject viewModel (Object1), pass a property (Object2) to another view (View2). Change value in View 2, and when i go back to View 1, i wish the value is updated too. What is the best solution?

In this Example, when i press the blue number, i wish black number is also updated. Actually I don't know why do the black number is updated after pressing button "Show". I would really appreciate if you could help me. Thanks.

import SwiftUI
import Combine

struct ContentView: View {
    @ObservedObject var object1: Object1 = Object1(ob: Object2(n: 0))
    @State var isShow = false
    var body: some View {
        NavigationView {
            VStack {
                Text("\(object1.object2.n)")
                //NavigationLink(destination: View2(object2: object1.object2)) {
                //     Text("Go to  view 2")
                //}   
                View2(object2: object1.object2)
                
                Button {
                    isShow = true
                } label: {
                    Text("Show")
                }.alert(isPresented: $isShow, content: {
                    Alert(title: Text("\(object1.object2.n)"))
                })
            }
        }
    }
}

struct View2: View {
    @ObservedObject var object2: Object2
    var body: some View {
        Button {
            object2.n += 1
        } label: {
            Text("\(object2.n)")
        }


    }
}

class Object1: ObservableObject {
    @Published var object2: Object2
    
    init(ob: Object2) {
        self.object2 = ob
    }
}

class Object2: ObservableObject {
    @Published var n: Int = 0
    init(n: Int) {
        self.n = n
    }
}


Here is possible solution:

    var body: some View {
        NavigationView {
            VStack {
                Text("\(object1.object2.n)")
                   .onChange(of: object1.object2.n) { _ in
                       object1.objectWillChange.send()
                   }

// .. other code

Alternate is to move every object2 dependent part into separated subview observed object2 explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM