在我看来,Apple 是在鼓励我们放弃在 SwiftUI 中使用 UIViewController
,但不使用 View Controller ,我觉得有点力不从心。我想要的是能够实现某种 ViewModel
,它将向 View
发出事件。
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,登录成功不知道怎么推送另一个controller
此外,对于如何以更好的方式实现我想要的任何建议,我将不胜感激。谢谢。
最佳答案
我找到了答案。如果你想显示回调的另一个 View ,你应该
创建状态
@State var pushActive = false
当 ViewModel 通知登录成功时,将
pushActive
设置为true
func handleSuccessfullLogin() { self.pushActive = true print("handleSuccessfullLogin") }
创建隐藏的
NavigationLink
并绑定(bind)到该状态NavigationLink(destination: ProfileView(viewModel: ProfileViewModelImpl()), isActive: self.$pushActive) { EmptyView() }.hidden()
关于ios - 在回调中以编程方式推送 View ,SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57315409/