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

时间:2020-05-10 18:08:30

标签: swiftui combine observableobject

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

如何在我的@State变量的地方使用我的@Published?

这是我的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)
  }
}

2 个答案:

答案 0 :(得分:0)

删除状态并直接使用视图模型成员,如下所示

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()
      }
    }
  }
}

答案 1 :(得分:0)

嘿,罗兰,我想你要找的是这个:

$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
    }
}