我的测试代码:
import SwiftUI
@main
struct TestingIOS14App: App {
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
.withHostingWindow { window in
let hostingController = UIHostingController(rootView: ContentView())
let mainNavigationController = UINavigationController(rootViewController: hostingController)
mainNavigationController.navigationBar.isHidden = true
window?.rootViewController = mainNavigationController
}
}
.onChange(of: scenePhase) { newScenePhase in
switch newScenePhase {
case .active:
print("App is active")
case .inactive:
print("App is inactive")
case .background:
print("App is in background")
@unknown default:
print("Oh - interesting: I received an unexpected new value.")
}
}
}
}
extension View {
func withHostingWindow(_ callback: @escaping (UIWindow?) -> Void) -> some View {
self.background(HostingWindowFinder(callback: callback))
}
}
struct HostingWindowFinder: UIViewRepresentable {
var callback: (UIWindow?) -> Void
func makeUIView(context: Context) -> UIView {
let view = UIView()
DispatchQueue.main.async { [weak view] in
self.callback(view?.window)
}
return view
}
func updateUIView(_ uiView: UIView, context: Context) { }
}
@Asperi's answer here和上面的代码似乎有效,但
除了最初启动应用程序的阶段外,场景生命周期.onChange(of:
似乎没有受到影响。不知道我做错了什么,请对此提供任何帮助。active
非常感谢 :)