在回调中以编程方式推送视图,SwiftUI [英] Push View programmatically in callback, SwiftUI
问题描述
在我看来,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 controllers, 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
.
视图模型:
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 push another controller if login is successful
此外,如果您有任何关于如何以更好的方式实现我想要的东西的建议,我将不胜感激.谢谢.
Also, I would appreciate any advice about how to implement what I want in a better way. Thanks.
推荐答案
我找到了答案.如果你想在回调中显示另一个视图,你应该
I've found the answer. If you want to show another view on callback you should
创建状态
@State var pushActive = false
当 ViewModel 通知登录成功时,将 pushActive
设置为 true
When ViewModel notifies that login is successful set pushActive
to true
func handleSuccessfullLogin() {
self.pushActive = true
print("handleSuccessfullLogin")
}
创建隐藏的NavigationLink
并绑定到那个状态
NavigationLink(destination:
ProfileView(viewModel: ProfileViewModelImpl()),
isActive: self.$pushActive) {
EmptyView()
}.hidden()
这篇关于在回调中以编程方式推送视图,SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!