在回调,SwiftUI中以编程方式推送View [英] Push View programmatically in callback, SwiftUI

查看:141
本文介绍了在回调,SwiftUI中以编程方式推送View的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,Apple鼓励我们放弃在SwiftUI中使用UIViewController,但是如果不使用视图控件,我会觉得有些无能为力.我想要的是能够实现某种ViewModel,它将向View发出事件.

It seems to me that Apple is encouraging us to give up using UIViewController in SwiftUI, but without using view controlelrs, I feel a little bit powerless. What I would like is to be able to implement some sort of ViewModel which will emit events to View.

ViewModel :

public protocol LoginViewModel: ViewModel {
  var onError: PassthroughSubject<Error, Never> { get }
  var onSuccessLogin: PassthroughSubject<Void, Never> { get }
}

查看:

public struct LoginView: View {
  fileprivate let viewModel: LoginViewModel

  public init(viewModel: LoginViewModel) {
    self.viewModel = viewModel
  }

  public var body: some View {
    NavigationView {
      MasterView()
        .onReceive(self.viewModel.onError, perform: self.handleError(_:))
        .onReceive(self.viewModel.onSuccessLogin, perform: self.handleSuccessfullLogin)
    }
  }

  func handleSuccessfullLogin() {
    //push next screen
  }

  func handleError(_ error: Error) {
    //show alert
  }
}

使用SwiftUI,我不知道如何实现以下目标:

Using SwiftUI, I don't know how to implement the following:

  • 如果登录成功,则推送另一个控制器
  • 如果发生错误,则显示警报

此外,如果您希望以更好的方式实现自己想要的东西,我将不胜感激.谢谢.

Also, I would appreciate any advice about how to implement what I want in a better way. Thanks.

更新1:我能够显示警报,但仍然找不到如何在viewModel的回调中推送另一个视图

Update 1: I was able to show an alert, but still cannot find how to push another view in viewModel's callback

推荐答案

我找到了答案.如果要在回调中显示其他视图,则应

I've found the answer. If you want to show another view on callback you should

1)创建状态@State var pushActive = false

2)当ViewModel通知登录成功时,将pushActive设置为true

2) When ViewModel notifies that login is successful set pushActive to true

  func handleSuccessfullLogin() {
    self.pushActive = true
    print("handleSuccessfullLogin")
  }

3)创建隐藏的NavigationLink并绑定到该状态

3) Create hidden NavigationLink and bind to that state

  NavigationLink(destination: ProfileView(viewModel: ProfileViewModelImpl()), isActive: self.pushActive) {
    Text("")
  }.hidden()

这篇关于在回调,SwiftUI中以编程方式推送View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆