当ObservedObject在其他类中更改时,如何在ContentView中运行方法[Swift 5 iOS 13.4]

问题描述 投票:0回答:1

这是我的基本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的变化并运行任何方法?

提前感谢!

ios swift view observableobject
1个回答
0
投票
有多种方法可以做到这一点。如果您想在运行RunThis()时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") } }

© www.soinside.com 2019 - 2024. All rights reserved.