抱歉,措辞很糟糕,但是在onAppear中,我正在更改一个State变量,但是除非在视图内部的某个地方使用该State变量,否则这不会重新渲染视图。
如果用户未登录,我试图弹出一个模式,但是除非我将变量放在如下所示的视图中,否则它将不会弹出
struct SearchView: View {
// Environment Variables
@EnvironmentObject var session: SessionStore
@State var sheetIsPresented: Bool = false
var body: some View {
NavigationView {
// Just having a line like this will cause it to work
if self.sheetIsPresented || !self.sheetIsPresented {}
}
.onAppear {
if self.session.userSession != nil {
self.sheetIsPresented = true
}
}
.sheet(isPresented: $sheetIsPresented) {
WelcomeSignInModal(sheetIsPresented: self.$sheetIsPresented)
}
}
}
答案 0 :(得分:0)
您可以尝试以下演示:
class SessionStore: ObservableObject {
var userSession: String? = "session"
}
struct ContentView: View {
@EnvironmentObject var session: SessionStore
@State var sheetIsPresented: Bool = false
var body: some View {
NavigationView {
Text("SearchView")
}
.onAppear {
self.sheetIsPresented = self.session.userSession != nil
}
.sheet(isPresented: $sheetIsPresented) {
Text("WelcomeSignInModal")
}
}
}
在Xcode 11.6,iOS 13.6上进行了测试