【发布时间】:2020-01-07 22:01:03
【问题描述】:
我在 ObservableObject 类中有一个已发布的变量isLoggedIn,如下所示:
import Combine
class UserAuth: ObservableObject{
@Published var isLoggedIn: Bool = false
}
我想在特定视图 (LoginView) 中将此变量更新为 true。这个变量决定了我向用户显示的视图,具体取决于用户是否登录:
struct ContentView: View {
@ObservedObject var userAuth = UserAuth()
var body: some View {
Group{
if(userAuth.isLoggedIn){
MainView()
}else{
AccountView()
}
}
}
}
因为 userAuth.isLoggedIn 为 false(我还没有登录)AccountView 显示出来了。
帐户视图:
struct AccountView: View {
@State private var toggleSheet = false
var body: some View {
VStack {
Spacer()
Button(action: {
self.toggleSheet.toggle()
}){
Text("Toggle Modal")
.padding()
.foregroundColor(Color.white)
.background(Color.blue)
.cornerRadius(10)
}
.sheet(isPresented: self.$toggleSheet){
LoginView()
}
Spacer()
}
}
}
每当用户按下按钮时,都会显示 LoginView 模式:
struct LoginView: View {
var body: some View {
VStack{
Button(action: {
return self.login()
}){
Text("Log in")
.padding()
.foregroundColor(Color.white)
.background(Color.green)
.cornerRadius(10)
}
}
}
func login(){
// update UserAuth().isLoggedIn to TRUE
}
}
在 LoginView 中有一个按钮,我想要的逻辑是让用户按下按钮,login() 被调用,并且在该函数内部 userAuth.isLoggedIn 设置为 true。实现这一点的最佳方法是什么?
我尝试直接更改该值,但出现以下错误:
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive
【问题讨论】: