在仔细检查Apple的SwiftUI文档,Web和stackoverflow之后,我似乎无法弄清楚如何使用多个类并在它们之间传递EnviromentObject数据。 SwiftUI的EnvironmentObject,ObservableObjects和Bindings上的所有文章都展示了如何将数据从模型传递到视图,但是如何从一个模型传递到另一个模型。还是我完全以错误的方式思考这个问题。
如何将@Published变量从A类传递到B类?
在这个简单的SwiftUI示例应用程序中,我试图将@Published数据从Settings类传递给NetworkManager类。此应用具有一个ContentView,其中包含两个用于用户名和密码的表单字段,并带有一个按钮,当按下该按钮时,它将与API联系并显示结果。
下面的代码将崩溃,因为NetworkManager mockService函数不知道什么是“设置”。我可以在View中读取观察到的“设置” EnvironmentObject,但是如何在另一个类中获取该数据呢?我猜这里与绑定有关,但不确定该怎么办。
场景代理:
...
var settings = Settings()
var networkManager = NetworkManager()
...
let contentView = ContentView()
.environmentObject(settings)
.environmentObject(networkManager)
...
ContentView.swift
class Settings: ObservableObject {
@Published var username: String = ""
@Published var password: String = ""
}
// This function in reality will be rewritten and expanded with multiple networking calls
class NetworkManager: ObservableObject {
@Published var token: String = ""
func mockService() {
token = settings.username + settings.password
}
}
struct ContentView: View {
@EnvironmentObject var settings: Settings
@EnvironmentObject var networkManager: NetworkManager
var body: some View {
VStack {
TextField("Username", text: $settings.username)
TextField("Password", text: $settings.password)
Button("Update"){
self.networkManager.mockService()
}
Divider()
Text("\(networkManager.token)")
}
}
}
答案 0 :(得分:1)
这是让网络对象知道设置对象的一种方法,但我认为这不是最好的方法,你可以试试:
class Settings: ObservableObject {
@Published var username: String = ""
@Published var password: String = ""
var currentSettingsPublisher: PassthroughSubject<Settings,Never> = .init()
var cancellablesBag: Set<AnyCancellable> = []
init() {
observeChanges()
}
// Object will change is called to notify subscribers about changes( That's how swiftUI react to changes)
private func observeChanges() {
self.objectWillChange.sink { [weak self] (_) in
guard let self = self else { return }
self.currentSettingsPublisher.send(self)
}.store(in: &cancellablesBag)
}
}
// This function in reality will be rewritten and expanded with multiple networking calls
class NetworkManager: ObservableObject {
@Published var token: String = ""
var cancellablesBag: Set<AnyCancellable> = []
var currentSettingsPublisher: AnyPublisher<Settings,Never>
private var settings: Settings?
init(_ settings: AnyPublisher<Settings,Never>) {
self.currentSettingsPublisher = settings
observeSettings()
}
func observeSettings() {
currentSettingsPublisher
// .debounce(for: .seconds(0.5), scheduler: RunLoop.main) maybe you can use debounce to debounce updating of your settings object
.sink { [weak self] (newSettings) in
guard let self = self else { return }
print("i have the new settings")
self.settings = newSettings
}.store(in: &cancellablesBag)
}
func mockService() {
guard let settings = settings else {
return assertionFailure("Settings is nil, what to do ?")
}
token = settings.username + settings.password
print("new token: \(token)")
}
}
struct ContentView: View {
@EnvironmentObject var settings: Settings
@EnvironmentObject var networkManager: NetworkManager
var body: some View {
VStack {
TextField("Username", text: $settings.username)
TextField("Password", text: $settings.password)
Button("Update"){
self.networkManager.mockService()
}
Divider()
Text("\(networkManager.token)")
}
}
}
和 SceneDelegate
var settings = Settings()
var networkManager: NetworkManager!
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
networkManager =
NetworkManager(settings.currentSettingsPublisher.eraseToAnyPublisher())
let contentView = ContentView()
.environmentObject(settings)
.environmentObject(networkManager)
}
答案 1 :(得分:0)
您需要以这种方式在ContentView上声明您的ObservableObject:
@ObservedObject声明对符合ObservableObject协议的引用类型的依赖:它实现了objectWillChange属性以将更改发布到其数据中。
@ObservedObject var settings: Settings
@ObservedObject var networkManager: NetworkManager