iOS:以编程方式创建的 UINavigationController 的导航栏未扩展到安全区域

iOS: Navigation Bar of a Programmatically created UINavigationController Not Expanding to Safe Area

我希望导航栏扩展到以编程方式创建的 UINavigationController 中的安全区域。我正在开发一个项目,他们以编程方式创建初始视图控制器并在 SceneDelegate 中设置其导航栏:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { 
    guard let windowScene = (scene as? UIWindowScene) else { return }
    
    window = UIWindow(windowScene: windowScene)
    let initialViewController = initViewController()
    let navigationCotnroller = UINavigationController(rootViewController: initialViewController)
    navigationBarConfiguration(navigationCotnroller)
    
    window?.rootViewController = navigationCotnroller
    window?.makeKeyAndVisible()
    
}

private func initViewController () -> UIViewController {
    let view_controller_to_be_returned = DeviceSearchVC()
    view_controller_to_be_returned.title = "Devices"
    return view_controller_to_be_returned
}

private func navigationBarConfiguration (_ controller: UINavigationController) {
    controller.navigationBar.prefersLargeTitles = true
    controller.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    controller.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    controller.navigationBar.tintColor = .white
    controller.navigationBar.backgroundColor = UIColor.systemBlue
}

看起来像这样:

我想让导航栏扩展到安全区域。

我试过这样的事情:

    extension UIViewController: UINavigationBarDelegate{
     
    func position(for bar: UIBarPositioning) -> UIBarPosition {
        return .topAttached
    }
}

但这没有用

只需将此添加到您的 navigationBarConfiguration func

的末尾
        if #available(iOS 13.0, *) {
            let navBarAppearance = UINavigationBarAppearance()
            navBarAppearance.configureWithOpaqueBackground()
            navBarAppearance.backgroundColor = UIColor.systemBlue
            controller.navigationBar.standardAppearance = navBarAppearance
            controller.navigationBar.scrollEdgeAppearance = navBarAppearance
        } else {
            controller.edgesForExtendedLayout = []
        }