当 ObservedObject 在其他 class [Swift 5 iOS 13.4] 中发生变化时如何 运行 ContentView 中的方法

How to run a method in ContentView when an ObservedObject changes in other class [Swift 5 iOS 13.4]

这是我的基本 ContentView

struct ContentView: View
{
    @ObservedObject var model = Model()

    init(model: Model)
    {
        self.model = model
    }

    // How to observe model.networkInfo's value over here and run "runThis()" whenever the value changes?

    func runThis()
    {
        // Function that I want to run
    }

    var body: some View
    {
        VStack
            {
            // Some widgets here
            }
        }
    }
}

这是我的模型

class Model: ObservableObject
{
    @Published var networkInfo: String
    {
        didSet
            {
                // How to access ContentView and run "runThis" method from there?
            }
    }
}

我不确定它是否可以访问?或者,如果我可以从 View 和 运行 任何方法观察 ObservableObject 的变化?

提前致谢!

有多种方法可以做到这一点。如果你想在 networkInfo 发生变化,那么你可以使用这样的东西:

class Model: ObservableObject {
    @Published var networkInfo: String = "" 
}


struct ContentView: View {
@ObservedObject var model = Model()

var body: some View {
    VStack {
        Button(action: {
            self.model.networkInfo = "test"
        }) {
            Text("change networkInfo")
        }
    }.onReceive(model.$networkInfo) { _ in self.runThis() }
   }

func runThis() {
      print("-------> runThis")
 }
 } 

另一种全局方式是这样的:

 class Model: ObservableObject {
   @Published var networkInfo: String = "" {
    didSet {
        NotificationCenter.default.post(name: NSNotification.Name("runThis"), object: nil)
    }
}
}

 struct ContentView: View {
@ObservedObject var model = Model()

var body: some View {
    VStack {
        Button(action: {
            self.model.networkInfo = "test"
        }) {
            Text("change networkInfo")
        }
    }.onReceive(
    NotificationCenter.default.publisher(for: NSNotification.Name("runThis"))) { _ in
        self.runThis()
    }
   }

func runThis() {
      print("-------> runThis")
 }
 }