如何将我的 SwiftUI 视图的 @State 换成我的视图模型 @Published 变量?

How to swap my @State of my SwiftUI view for my view model @Published variable?

我有一个按钮可以触发我的视图状态。因为我现在已经添加了一个网络调用,所以我希望我的视图模型用它的 @Publihed 变量替换 @State 以执行相同的更改。

如何使用我的@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([=11=]) },
        receiveValue: {
          // My credentials
          print("Login: \([=11=].login)\nToken: \([=11=].token)")
          DispatchQueue.main.async {
            // Once I am logged in, I want this
            // value to change my view.
            self.isLoggedIn = true } })
      .store(in: &subscriptions)
  }
}

移除状态,直接使用视图模型成员,如下

struct ContentView: View {

  @ObservedObject var viewModel = OnboardingViewModel()

  var body: some View {
    ZStack {
      Button(action: {
        self.viewModel.demoLogin()
      }) {
        Text("Log in")
      }

      if viewModel.isLoggedIn {    // << here !!
        TutorialView()
      }
    }
  }
}

嘿 Roland 我想你要找的是这个:

$viewMode.isLoggedIn

在 var 之前添加 $ 将确保 SwiftUI 知道它的值更改。

struct ContentView: View {

  @ObservedObject var viewModel = OnboardingViewModel()

  var body: some View {
    ZStack {
      Button(action: {
        viewModel.login()
      }) {
        Text("Log in")
      }

      if $viewMode.isLoggedIn {
        TutorialView()
      }
    }
  }
}



class OnboardingViewModel: ObservableObject {

    @Published var isLoggedIn = false

    
    func login() {
       isLoggedIn = true
    }
}