当 ObservedObject 在其他类中发生更改时如何在 ContentView 中运行方法 [Swift 5 iOS 13.4]
Posted
技术标签:
【中文标题】当 ObservedObject 在其他类中发生更改时如何在 ContentView 中运行方法 [Swift 5 iOS 13.4]【英文标题】:How to run a method in ContentView when an ObservedObject changes in other class [Swift 5 iOS 13.4] 【发布时间】:2020-04-09 08:10:33 【问题描述】:这是我的基本内容视图
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 的变化并运行任何方法?
提前致谢!
【问题讨论】:
【参考方案1】:有很多方法可以做到这一点。如果你想 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")
【讨论】:
这实际上很有帮助。非常感谢@workingdog,因为你,我现在将更多地了解有用的 onReceive() !!!以上是关于当 ObservedObject 在其他类中发生更改时如何在 ContentView 中运行方法 [Swift 5 iOS 13.4]的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI:属性装饰器的理解@State,@Binding,@ObservedObject,@Published,@Environment,@EnvironmentObject
SwiftUI:属性装饰器的理解@State,@Binding,@ObservedObject,@Published,@Environment,@EnvironmentObject