我有一个按钮可以触发我的视图状态。由于我现在添加了一个网络调用,我希望我的视图模型将 @State 替换为其 @Publihed 变量以执行相同的更改。
如何使用我的@Published 代替我的@State 变量?
所以这是我的 SwiftUI 视图:
struct ContentView: View {
@ObservedObject var viewModel = OnboardingViewModel()
// This is the value I want to use as @Publisher
@State var isLoggedIn = false
var body: some View {
ZStack {
Button(action: {
// Before my @State was here
// self.isLoggedIn = true
self.viewModel.login()
}) {
Text("Log in")
}
if isLoggedIn {
TutorialView()
}
}
}
}
这是我的模型:
final class OnboardingViewModel: ObservableObject {
@Published var isLoggedIn = false
private var subscriptions = Set<AnyCancellable>()
func demoLogin() {
AuthRequest.shared.login()
.sink(
receiveCompletion: { print($0) },
receiveValue: {
// My credentials
print("Login: \($0.login)\nToken: \($0.token)")
DispatchQueue.main.async {
// Once I am logged in, I want this
// value to change my view.
self.isLoggedIn = true } })
.store(in: &subscriptions)
}
}