这是我的基本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的变化并运行任何方法?
提前感谢!
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") } }