58 lines
1.7 KiB
Swift
58 lines
1.7 KiB
Swift
//
|
||
// AppRouter.swift
|
||
// suixinkan
|
||
//
|
||
|
||
import UIKit
|
||
|
||
/// 应用根页面路由。
|
||
enum AppRouter {
|
||
|
||
enum Root {
|
||
case login
|
||
case mainTab
|
||
}
|
||
|
||
/// 根据登录态创建根控制器:已登录 → 主页 Tab,未登录 → 登录页。
|
||
static func makeRootViewController() -> UIViewController {
|
||
makeViewController(for: AppStore.shared.isLoggedIn ? .mainTab : .login)
|
||
}
|
||
|
||
/// 切换窗口根控制器。
|
||
static func setRoot(_ root: Root, on window: UIWindow?, animated: Bool = true) {
|
||
setRoot(makeViewController(for: root), on: window, animated: animated)
|
||
}
|
||
|
||
/// 根据当前登录态刷新根控制器。
|
||
static func refreshRoot(on window: UIWindow?, animated: Bool = true) {
|
||
setRoot(AppStore.shared.isLoggedIn ? .mainTab : .login, on: window, animated: animated)
|
||
}
|
||
|
||
private static func makeViewController(for root: Root) -> UIViewController {
|
||
switch root {
|
||
case .login:
|
||
return UINavigationController(rootViewController: LoginViewController())
|
||
case .mainTab:
|
||
return MainTabBarController()
|
||
}
|
||
}
|
||
|
||
private static func setRoot(_ viewController: UIViewController, on window: UIWindow?, animated: Bool) {
|
||
guard let window else { return }
|
||
|
||
guard animated, let snapshot = window.snapshotView(afterScreenUpdates: true) else {
|
||
window.rootViewController = viewController
|
||
return
|
||
}
|
||
|
||
viewController.view.addSubview(snapshot)
|
||
window.rootViewController = viewController
|
||
|
||
UIView.animate(withDuration: 0.25, animations: {
|
||
snapshot.alpha = 0
|
||
}, completion: { _ in
|
||
snapshot.removeFromSuperview()
|
||
})
|
||
}
|
||
}
|