1

我的测试代码:

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

非常感谢 :)

4

1 回答 1

0

您的代码和您链接到的答案之间的区别在于您完全替换了应用程序的视图层次结构。注意他们如何使用

if let controller = window?.rootViewController

相反,您正在分配一个新的根视图控制器

window?.rootViewController = mainNavigationController

我的猜测是这就是导致您的问题的原因。

但是,如果您只想隐藏导航栏,可以使用 SwiftUI 方法来做到这一点。

于 2021-07-01T11:40:05.667 回答