Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe Area and Navigation Bar

I'm trying to add a Navigation Bar in a xib, but the navigation bar does not fill to the top, it leaves space above it where the camera notch is. See the screenshot below:

enter image description here

Here are my constraints for the Navigation Bar:

enter image description here

I've also tried setting the top constraint for the Navigation Bar to the Superview. This is the result of that:

enter image description here

I can't believe it is this difficult. What a I missing here?

like image 851
tentmaking Avatar asked Dec 11 '18 18:12

tentmaking


2 Answers

  1. You should have @IBOutlet of your navigation bar (or reference if navigation bar is made programmatically). Also, keep the bar's top constraint to Safe area.
  2. Make your ViewController conform to UINavigationBarDelegate and set delegate of navigation bar (navigationBar.delegate = self)
  3. Implement this function and return .topAttached:
func position(for bar: UIBarPositioning) -> UIBarPosition {
 return .topAttached
}
like image 172
Ondřej Korol Avatar answered Sep 20 '22 17:09

Ondřej Korol


You almost never want to add a UINavigationBar directly to a view controller's view, rather you want embed your view controller in a UINavigationController. If you're using storyboards, you can do this by selected your view controller, clicking the Editor menu -> Embed In -> Navigation Controller.

If not using storyboards you can create a view controller, and set it as the root view controller of UINavigationController. Then present the navigation controller or embed that navigation controller in a tab controller or split controller.

let mySpecialViewController = MySpecialViewController()
let navigationController = UINavigationController(rootViewController: mySpecialViewController)
present(navigationController, animated: true)

This code above needs to be called from inside a UIViewController subclass.

If you are doing this from your app delegate to set up the initial view controller of your app, you can do it like so:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let mySpecialViewController = MySpecialViewController()
    let navigationController = UINavigationController(rootViewController: mySpecialViewController)
    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()
    return true
}
like image 31
beyowulf Avatar answered Sep 20 '22 17:09

beyowulf