我正在尝试使用@EnvironmentObject为我的应用程序创建路由器对象。但是问题在于,更新根视图类型时,@ Published属性不会更新根视图。
这是我的下面的代码。
MainApp.swift
var body: some Scene {
WindowGroup {
RootView().environmentObject(ViewRouter())
}
}
ViewRouter.swift
Code Block
enum Page {
case signin
case tasklist
}
final class ViewRouter: ObservableObject {
@Published var currentPage: Page = .signin
}
RootView.swift
struct RootView: View {
@EnvironmentObject var router: ViewRouter
var body: some View {
if router.currentPage == .signin {
SigninView()
} else {
TaskListView()
}
}
}
SigninView.swift
struct SigninView: View {
@EnvironmentObject var router: ViewRouter
@State var signInHandler: SignInWithAppleCoordinator?
var window: UIWindow? {
guard let scene = UIApplication.shared.connectedScenes.first,
let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate,
let window = windowSceneDelegate.window else {
return nil
}
return window
}
var body: some View {
MyAppleIDButton().colorScheme(.light)
.frame(width: 280, height: 38, alignment: .center)
.onTapGesture {
signInWithAppleButtonTapped()
}
}
func signInWithAppleButtonTapped() {
guard let _window = self.window else { return }
signInHandler = SignInWithAppleCoordinator(window: _window)
signInHandler?.signIn { (user) in
router.currentPage = .tasklist
}
}
}
我想我找到了这个问题的答案。
我创建了一个状态isLoggedIn
,用于检查Sign in with Apple
是否成功完成。
@State var isLoggedIn: Bool = false
然后我添加了 View Modifier onChange
,它正在检查上面isLoggedIn的值更改。在onChange
内部,我为router.currentPage
分配了一个新值,如下所示。
.onChange(of: isLoggedIn, perform: { isLoggedIn in
if isLoggedIn {
router.currentPage = .tasklist
} else {
router.currentPage = .signin
}
})
但是我仍然不确定为什么在SigninWithApple按钮的关闭中不起作用。