gpt4 book ai didi

ios - 在 SwiftUI 中将 NavigationButton 与服务器请求一起使用

转载 作者:搜寻专家 更新时间:2023-10-31 19:31:54 30 4
gpt4 key购买 nike

如何让 NavigationButton 在进入下一个 View 之前等待服务器响应?

我试过这样的事情

NavigationButton(destination: LogonView(),  onTrigger: { () -> Bool in
return self.viewModel.responseReceived
}) {
Text("OK")
}.tapAction {
self.viewModel.fetch(companyID: &self.companyID)
}

但是 tapAction 从未被调用。

我使用 Button 让它工作:

Button(action: {
self.viewModel.fetch(companyID: &self.companyID)
}) {
Text("OK")
}.presentation(viewModel.shouldPresentModal ? Modal(LogonView() : nil)

// in ViewModel
var shouldPresentModal = false { // set to true when data are received from server
didSet {
didChange.send(())
}
}

但我需要在导航中显示下一个 View ,而不是模态

谢谢!

最佳答案

Sorin,至少在我看来,SwiftUI 是专为表示层设计的,它不应该取代您的模型。而且它是“ react 性的”,与 UIKit 不同,因此从设计上讲,让 View 执行类似模型的操作非常困难。

我会这样处理任务:

class LoginModel : BindableObject {

var didChange = PassthroughSubject<LoginModel, Never>()

private(set) var username: String? {
didSet {
didChange.send(self)
}
}

func load() {
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
self.username = "Sorin"
}
}
}

这是封装我们登录代码的模型对象。此处通过简单的延迟来模拟异步操作。

然后是 View :

public struct LoginScreen: View {

@ObjectBinding var loginObject = LoginModel()

public var body: some View {
Group {
if login.username == nil {
Text("Trying to login, please wait...")
} else {
Text("Successful login, the username is \(loginObject.username!)")
}
}.onAppear {
self.loginObject.load()
}
}
}

与模型对象“链接”有更好的方法,但显然我们在这里只看一个简单的例子。

您的 NavigationButton 将只链接到 LoginScreen,没有任何其他代码或触发器。屏幕最初会显示 Trying to login, please wait... 5 秒后将变为 Successful login, the username is Sorin。显然,您可以疯狂地将我的文字替换为您想要的任何内容。

关于ios - 在 SwiftUI 中将 NavigationButton 与服务器请求一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56595542/

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