1

我有一个按钮可以触发我的视图状态。由于我现在添加了一个网络调用,我希望我的视图模型将 @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)
  }
}
4

2 回答 2

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()
      }
    }
  }
}
于 2020-05-10T18:25:06.837 回答
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
    }
}
于 2021-07-28T21:15:19.227 回答