gpt4 book ai didi

binding - SwiftUI 在多个类之间传递数据

转载 作者:行者123 更新时间:2023-12-04 11:36:38 25 4
gpt4 key购买 nike

在搜索了 Apple 的 SwiftUI 文档、网络和 stackoverflow 之后,我似乎无法弄清楚如何使用多个类并在它们之间传递 EnviromentObject 数据。所有关于 SwiftUI 的 EnvironmentObject、ObservableObjects、Bindings 的文章都展示了如何将数据从模型传递到 View ,但如何从一个模型传递到另一个模型。或者我完全以错误的方式思考这个问题。

如何将@Published var 从 A 类传递到 B 类?

在这个简单的 SwiftUI 示例应用程序中,我试图将 @Published 数据从 Settings 类传递到 NetworkManager 类。此应用程序有一个 ContentView,其中包含用户名和密码的两个表单字段,并带有一个按钮,按下该按钮将联系 API 并显示结果。

下面的代码会崩溃,因为 NetworkManager mockService 函数不知道“设置”是什么。我可以在 View 中读取“设置”观察到的 EnvironmentObject,但是如何在另一个类中获取该数据?我猜这里与绑定(bind)有关,但不确定该怎么做。

场景委托(delegate):

...
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)")

}
}
}

最佳答案

这是使网络对象知道设置对象的一种方法,但我认为这不是最好的方法,您可以尝试一下:

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)

}

关于binding - SwiftUI 在多个类之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59299410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com