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:
Here are my constraints for the Navigation Bar:
I've also tried setting the top constraint for the Navigation Bar to the Superview. This is the result of that:
I can't believe it is this difficult. What a I missing here?
UINavigationBarDelegate
and set delegate of navigation bar (navigationBar.delegate = self
)func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With