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

Time:09-26

I want the navigation bar to expand to safe area in a programmatically created UINavigationController. I'm working on a project where they create the initial view controller programmatically and setup its navigation bar in the 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
}

It looks like this: enter image description here

I want the navigation bar to expand to the safe area.

I tried something like this:

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

but that didn't work

CodePudding user response:

Just add this to the end of your 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 = []
        }

enter image description here

  • Related