Using UINavigationBar standalone causes weird top attaching layout

Against using UINavigationController + UINavigationBar. This question is about what if we use UINavigationBar as standalone in a ViewController.

To lay UINavigationBar out as well as it is the case of UINavigationController management, I'm doing like this,

  • Add UINavigationBar to the view of ViewController

  • Add constraints to lay it out on top of the safe area.

navigationBar.bottom == safeAreaLayoutGuide.top navigationBar.left == view.left navigationBar.right == view.right

  • Set the delegate of UINavigationBar, then return topAttached for the bar position.
  • Set additionalSafeAreaInsets to propagate the insets to the subviews.

It looks works well but got weird laying out inside UINavigationBar from seeing view debugger.

The extending view to cover to the top of the screen by setting `topAttached is too much growing.

What am I missing? I'd like to know how to use UINavigationBar in the correct way that includes safe-area management.

Replies

class ViewController: UIViewController {
    @IBOutlet weak var navigationBar: UINavigationBar!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        navigationBar.delegate = self
    }
}

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

  • Hi, Thank you for your answer. I have a question, how do you manage safe-area layout guide? If we don't set additional-safe-area-insets, the child view controllers or views lay their contents behind the UINavigationBar.

  • For instance, like this tree

    - ViewController - View - UINavigationBar - UICollectionView (laying out to fullscreen, content-inset managed by safe-area)
Add a Comment

Additional notes for my question, I'm working on this like

- ViewController
  - View
    - UINavigationBar
    - UICollectionView (laying out to fullscreen, content-inset managed by safe-area)