SwiftUI 认证视图 [英] SwiftUI authentication view
问题描述
在 swift UI 中,我希望内容视图成为我的应用程序的根视图,并带有条件设置以检查用户是否已登录.如果用户登录列表视图,则显示其他明智的登录视图,以便用户可以登录.根据我的研究,我找不到最好的方法来做到这一点.
In swift UI I want the content view to be my root view for my app with a conditional setup to check if the users is logged in or not. If the user is logged in a list view shows other wise show the login view so the user can log in. Based on my research i could not find a best way to do this.
在我的情况下,我无法找到可行的解决方案,也不知道它是否是最佳解决方案.
In my case I can not get the solution I found to work and do not know if it is the best solution.
import SwiftUI
struct ContentView: View {
@ObservedObject var userAuth: UserAuth = UserAuth()
// MARK: - View
@ViewBuilder
var body: some View {
if !userAuth.isLoggedin {
return LoginView().environmentObject(userAuth)
}
return BookList()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import Combine
class UserAuth: ObservableObject {
let didChange = PassthroughSubject<UserAuth,Never>()
// required to conform to protocol 'ObservableObject'
let willChange = PassthroughSubject<UserAuth,Never>()
func login() {
// login request... on success:
self.isLoggedin = true
}
func logout() {
// login request... on success:
self.isLoggedin = false
}
var isLoggedin = false {
didSet {
didChange.send(self)
}
// willSet {
// willChange.send(self)
// }
}
}
运行时,我得到的只是一个白屏.似乎视图构建器可能是问题所在,但删除了我在内容视图上出现不透明错误
When running this all i get is a white screen. It seems that the view builder might be the problem but removing that i get a opaque error on content view
推荐答案
提供的代码快照有两个问题:1) 视图构建器内容不正确,以及 2) 模型不正确.
There two problems with provided code snapshot: 1) incorrect view builder content, and 2) incorrect model.
见下文,两者均已修复.使用 Xcode 11.4/iOS 13.4 测试
See below both fixed. Tested with Xcode 11.4 / iOS 13.4
struct ContentView: View {
@ObservedObject var userAuth: UserAuth = UserAuth()
// MARK: - View
@ViewBuilder // no need return inside
var body: some View {
if !userAuth.isLoggedin {
LoginView().environmentObject(userAuth)
}
else {
BookList()
}
}
}
import Combine
class UserAuth: ObservableObject {
@Published var isLoggedin = false // published property to update view
func login() {
// login request... on success:
self.isLoggedin = true
}
func logout() {
// login request... on success:
self.isLoggedin = false
}
}
这篇关于SwiftUI 认证视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!