1

这是我的基本内容视图

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 的变化并运行任何方法?

提前致谢!

4

1 回答 1

1

有很多方法可以做到这一点。如果您想在 networkInfo 更改时 runThis() ,那么您可以使用以下内容:

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")
 }
 }
于 2020-04-09T09:17:10.530 回答